<commit_before>'use strict';

angular.module('ddsApp').controller('FoyerLogementCtrl', function($scope, $http, $log, logementTypes, locationTypes, loyerLabels, ImpactStudyService, SituationService, IndividuService) {
    var logement = $scope.logement = {
        adresse: {},
        inhabitantForThreeYearsOutOfLastFive: true
    };
    if ($scope.situation.logement) {
        logement = $scope.logement = _.merge(logement, $scope.situation.logement);
    }

    $scope.logementTypes = logementTypes;
    $scope.locationTypes = locationTypes;
    $scope.demandeur = SituationService.getDemandeur($scope.situation);

    function cityStartsWith(prefix) {
        return logement.adresse.nomCommune && logement.adresse.nomCommune.indexOf(prefix.toUpperCase()) === 0;
    }

    $scope.yearsAgo = function yearsAgo(amount) {
        return moment().subtract(amount, 'years').format('MMMM YYYY');
    };

    $scope.captureCharges = function() {
            return (logement.type == 'locataire') && (logement.locationType !== 'meublehotel');
    };

    $scope.loyerLabel = function() {
        var result = loyerLabels[logement.type];
        if (logement.type === 'locataire') {
            if ($scope.captureCharges()) {
                result += ' (hors charges)';
            } else {
                result += ' (charges comprises)';
            }
        }

        return result;
    };

    $scope.captureColocation= function() {
        return logement.type == 'locataire';
    };

    $scope.captureMembreFamilleProprietaire = function() {
        return logement.type == 'locataire' && angular.isDefined(logement.colocation);
    };

    $scope.captureLocationType = function() {
        return logement.type == 'locataire' && angular.isDefined(logement.membreFamilleProprietaire);
    };

    $scope.captureChambre = function() {
        return logement.type == 'locataire' && 'foyer' !== logement.locationType && angular.isDefined(logement.locationType);
    };

    $scope.captureHabiteChezParents = function() {
        var age = IndividuService.age($scope.demandeur);
        return (logement.type == 'heberge') && $scope.demandeur.fiscalementIndependant && (age >= 18) && (age < 25) && (! SituationService.hasEnfant($scope.situation));
    };

    $scope.captureParticipationFrais = function() {
        return (logement.type == 'heberge') && (! $scope.captureHabiteChezParents() || angular.isDefined($scope.demandeur.habiteChezParents));
    };

    $scope.captureLoyer = function() {
        if (logement.type == 'heberge') {
            return false;
        }
        return _.any([
            angular.isDefined(logement.primoAccedant),
            logement.locationType == 'foyer',
            angular.isDefined(logement.isChambre)
        ]);
    };

    $scope.captureCodePostal = function() {
        return _.any([
            angular.isDefined(logement.primoAccedant),
            logement.locationType == 'foyer',
            angular.isDefined(logement.isChambre),
            logement.type == 'heberge' && angular.isDefined(logement.participationFrais),
            logement.type == 'sansDomicile'
        ]);
    };

    $scope.captureResidentParis = function() {
        return $scope.captureCodePostal() && logement.type != 'sansDomicile' && cityStartsWith('Paris');
    };

    $scope.changeLogementType = function() {
        ['colocation', 'locationType', 'membreFamilleProprietaire', 'primoAccedant', 'loyer', 'charges', 'isChambre'].forEach(function(field) {
            delete logement[field];
        });
        logement.loyer = 0;
    };

    $scope.updateCities = function updateCities() {
        if (! $scope.logement.postalCode)
            return;  // the user has made the value invalid since we were called

        $scope.retrievingCities = true;

        $http.get('/api/outils/communes/' + $scope.logement.postalCode)
             .then(function(result) {
                  $scope.cities = result.data;
                  logement.adresse = $scope.cities[0] || {};
              }, $log.error.bind($log)
              ).finally(function() {
                  $scope.retrievingCities = false;
              });
    };

    $scope.submit = function(form) {
        $scope.submitted = true;
        if (form.$valid && logement.adresse) {
            logement.inhabitantForThreeYearsOutOfLastFive = logement.inhabitantForThreeYearsOutOfLastFive && cityStartsWith('Paris');
            $scope.$emit('logement', logement);
            ImpactStudyService.sendPostCode($scope.situation);
        }
    };
});
<commit_msg>Clean fields when changing logements types<commit_after>'use strict';

angular.module('ddsApp').controller('FoyerLogementCtrl', function($scope, $http, $log, logementTypes, locationTypes, loyerLabels, ImpactStudyService, SituationService, IndividuService) {
    var logement = $scope.logement = {
        adresse: {},
        inhabitantForThreeYearsOutOfLastFive: true
    };
    if ($scope.situation.logement) {
        logement = $scope.logement = _.merge(logement, $scope.situation.logement);
    }

    $scope.logementTypes = logementTypes;
    $scope.locationTypes = locationTypes;
    $scope.demandeur = SituationService.getDemandeur($scope.situation);

    function cityStartsWith(prefix) {
        return logement.adresse.nomCommune && logement.adresse.nomCommune.indexOf(prefix.toUpperCase()) === 0;
    }

    $scope.yearsAgo = function yearsAgo(amount) {
        return moment().subtract(amount, 'years').format('MMMM YYYY');
    };

    $scope.captureCharges = function() {
            return (logement.type == 'locataire') && (logement.locationType !== 'meublehotel');
    };

    $scope.loyerLabel = function() {
        var result = loyerLabels[logement.type];
        if (logement.type === 'locataire') {
            if ($scope.captureCharges()) {
                result += ' (hors charges)';
            } else {
                result += ' (charges comprises)';
            }
        }

        return result;
    };

    $scope.captureColocation= function() {
        return logement.type == 'locataire';
    };

    $scope.captureMembreFamilleProprietaire = function() {
        return logement.type == 'locataire' && angular.isDefined(logement.colocation);
    };

    $scope.captureLocationType = function() {
        return logement.type == 'locataire' && angular.isDefined(logement.membreFamilleProprietaire);
    };

    $scope.captureChambre = function() {
        return logement.type == 'locataire' && 'foyer' !== logement.locationType && angular.isDefined(logement.locationType);
    };

    $scope.captureHabiteChezParents = function() {
        var age = IndividuService.age($scope.demandeur);
        return (logement.type == 'heberge') && $scope.demandeur.fiscalementIndependant && (age >= 18) && (age < 25) && (! SituationService.hasEnfant($scope.situation));
    };

    $scope.captureParticipationFrais = function() {
        return (logement.type == 'heberge') && (! $scope.captureHabiteChezParents() || angular.isDefined($scope.demandeur.habiteChezParents));
    };

    $scope.captureLoyer = function() {
        if (logement.type == 'heberge') {
            return false;
        }
        return _.any([
            angular.isDefined(logement.primoAccedant),
            logement.locationType == 'foyer',
            angular.isDefined(logement.isChambre)
        ]);
    };

    $scope.captureCodePostal = function() {
        return _.any([
            angular.isDefined(logement.primoAccedant),
            logement.locationType == 'foyer',
            angular.isDefined(logement.isChambre),
            logement.type == 'heberge' && angular.isDefined(logement.participationFrais),
            logement.type == 'sansDomicile'
        ]);
    };

    $scope.captureResidentParis = function() {
        return $scope.captureCodePostal() && logement.type != 'sansDomicile' && cityStartsWith('Paris');
    };

    $scope.changeLogementType = function() {
        ['colocation', 'locationType', 'membreFamilleProprietaire', 'primoAccedant', 'loyer', 'charges', 'isChambre', 'participationFrais'].forEach(function(field) {
            delete logement[field];
        });
        logement.loyer = 0;
        delete $scope.demandeur.habiteChezParents;
    };

    $scope.updateCities = function updateCities() {
        if (! $scope.logement.postalCode)
            return;  // the user has made the value invalid since we were called

        $scope.retrievingCities = true;

        $http.get('/api/outils/communes/' + $scope.logement.postalCode)
             .then(function(result) {
                  $scope.cities = result.data;
                  logement.adresse = $scope.cities[0] || {};
              }, $log.error.bind($log)
              ).finally(function() {
                  $scope.retrievingCities = false;
              });
    };

    $scope.submit = function(form) {
        $scope.submitted = true;
        if (form.$valid && logement.adresse) {
            logement.inhabitantForThreeYearsOutOfLastFive = logement.inhabitantForThreeYearsOutOfLastFive && cityStartsWith('Paris');
            $scope.$emit('logement', logement);
            ImpactStudyService.sendPostCode($scope.situation);
        }
    };
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2019 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import {replaceTags} from '../shared/helpers/tags'
import React from 'react'
import PropTypes from 'prop-types'
import ExternalToolDialogModal from './ExternalToolDialog/Modal'
import ExternalToolDialogTray from './ExternalToolDialog/Tray'
import Alert from '@instructure/ui-alerts/lib/components/Alert'
import I18n from 'i18n!ExternalToolDialog'
import {send} from '../shared/rce/RceCommandShim'
import TinyMCEContentItem from 'tinymce_plugins/instructure_external_tools/TinyMCEContentItem'
import FlexItem from '@instructure/ui-layout/lib/components/Flex/FlexItem'
import processEditorContentItems from '../deep_linking/processors/processEditorContentItems'

const EMPTY_BUTTON = {
  height: 300,
  width: 400,
  name: ' '
}

const EMPTY_FORM = {
  url: '',
  selection: '',
  contents: ''
}

export default class ExternalToolDialog extends React.Component {
  static propTypes = {
    win: PropTypes.shape({
      addEventListener: PropTypes.func.isRequired,
      removeEventListener: PropTypes.func.isRequired,
      confirm: PropTypes.func.isRequired,
      height: PropTypes.number.isRequired,
      $: PropTypes.func.isRequired
    }).isRequired,
    editor: PropTypes.shape({
      id: PropTypes.string.isRequired,
      selection: PropTypes.shape({
        getContent: PropTypes.func.isRequired
      }),
      getContent: PropTypes.func.isRequired
    }).isRequired,
    contextAssetString: PropTypes.string.isRequired,
    iframeAllowances: PropTypes.string.isRequired,
    resourceSelectionUrl: PropTypes.string,
    deepLinkingOrigin: PropTypes.string
  }

  static defaultProps = {
    resourceSelectionUrl: null,
    deepLinkingOrigin: ''
  }

  state = {
    open: false,
    button: EMPTY_BUTTON,
    infoAlert: null,
    form: EMPTY_FORM
  }

  open(button) {
    const {win, editor, contextAssetString, resourceSelectionUrl} = this.props
    let url = replaceTags(resourceSelectionUrl, 'id', button.id)
    const selection = editor.selection.getContent() || ''
    const contents = editor.getContent() || ''
    if (url == null) {
      // if we don't have a url on the page, build one using the current context.
      // url should look like: /courses/2/external_tools/15/resoruce_selection?editor=1
      const asset = contextAssetString.split('_')
      url = `/${asset[0]}s/${asset[1]}/external_tools/${button.id}/resource_selection`
    }
    this.setState({open: true, button, form: {url, selection, contents}})
    win.addEventListener('beforeunload', this.handleBeforeUnload)
    win.addEventListener('message', this.handleDeepLinking)
    win.$(win).bind('externalContentReady', this.handleExternalContentReady)
  }

  close() {
    const {win} = this.props
    win.removeEventListener('beforeunload', this.handleBeforeUnload)
    win.removeEventListener('message', this.handleDeepLinking)
    win.$(win).unbind('externalContentReady')
    this.setState({open: false, form: EMPTY_FORM})
  }

  handleBeforeUnload = ev => (ev.returnValue = I18n.t('Changes you made may not be saved.'))

  handleExternalContentReady = (ev, data) => {
    const {editor, win} = this.props
    const contentItems = data.contentItems
    if (contentItems.length === 1 && contentItems[0]['@type'] === 'lti_replace') {
      const code = contentItems[0].text
      send(win.$(`#${editor.id}`), 'set_code', code)
    } else {
      for (let i = 0, len = contentItems.length; i < len; ++i) {
        const code = TinyMCEContentItem.fromJSON(contentItems[i]).codePayload
        send(win.$(`#${editor.id}`), 'insert_code', code)
      }
    }
    this.close()
  }

  handleDeepLinking = ev => {
    const {editor, deepLinkingOrigin} = this.props
    // Only accept messages from the same origin
    if (
      ev.origin === deepLinkingOrigin &&
      ev.data &&
      ev.data.messageType === 'LtiDeepLinkingResponse'
    ) {
      processEditorContentItems(ev, editor, this)
    }
  }

  handleClose = () => {
    const {win} = this.props
    const msg = I18n.t('Are you sure you want to cancel? Changes you made may not be saved.')
    if (win.confirm(msg)) {
      this.close()
    }
  }

  handleOpen = () => this.formRef.submit()

  handleRemove = () => {
    this.setState({button: EMPTY_BUTTON})
  }

  handleInfoAlertFocus = ev => this.setState({infoAlert: ev.target})

  handleInfoAlertBlur = () => this.setState({infoAlert: null})

  render() {
    const {open, button, form, infoAlert} = this.state
    const {iframeAllowances, win} = this.props
    const label = I18n.t('embed_from_external_tool', 'Embed content from External Tool')
    const frameHeight = Math.max(Math.min(win.height - 100, 550), 100)
    const Overlay = button.use_tray ? ExternalToolDialogTray : ExternalToolDialogModal
    return (
      <React.Fragment>
        <form
          ref={ref => (this.formRef = ref)}
          method="POST"
          action={form.url}
          target="external_tool_launch"
          style={{margin: 0}}
        >
          <input type="hidden" name="editor" value="1" />
          <input type="hidden" name="selection" value={form.selection} />
          <input type="hidden" name="editor_contents" value={form.contents} />
        </form>
        <Overlay
          open={open}
          label={label}
          onOpen={this.handleOpen}
          onClose={this.handleRemove}
          onCloseButton={this.handleClose}
          closeLabel={I18n.t('Close')}
          name={button.name}
        >
          <FlexItem>
            <div
              ref={ref => (this.beforeInfoAlertRef = ref)}
              tabIndex="0" // eslint-disable-line jsx-a11y/no-noninteractive-tabindex
              onFocus={this.handleInfoAlertFocus}
              onBlur={this.handleInfoAlertBlur}
              className={
                infoAlert && infoAlert === this.beforeInfoAlertRef ? '' : 'screenreader-only'
              }
            >
              <Alert margin="small">{I18n.t('The following content is partner provided')}</Alert>
            </div>
          </FlexItem>
          <FlexItem>
            <iframe
              title={label}
              ref={ref => (this.iframeRef = ref)}
              name="external_tool_launch"
              src="/images/ajax-loader-medium-444.gif"
              id="external_tool_button_frame"
              style={{
                flexGrow: '1',
                flexShrink: '1',
                width: button.use_tray ? undefined : button.width || 800,
                height: button.use_tray ? undefined : button.height || frameHeight,
                border: '0'
              }}
              allow={iframeAllowances}
              borderstyle="0"
            />
          </FlexItem>
          <FlexItem>
            <div
              ref={ref => (this.afterInfoAlertRef = ref)}
              tabIndex="0" // eslint-disable-line jsx-a11y/no-noninteractive-tabindex
              onFocus={this.handleInfoAlertFocus}
              onBlur={this.handleInfoAlertBlur}
              className={
                infoAlert && infoAlert === this.afterInfoAlertRef ? '' : 'screenreader-only'
              }
            >
              <Alert margin="small">{I18n.t('The preceding content is partner provided')}</Alert>
            </div>
          </FlexItem>
        </Overlay>
      </React.Fragment>
    )
  }
}
<commit_msg>Revert "Fix ExternalToolDialog rendering error"<commit_after>/*
 * Copyright (C) 2019 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import {replaceTags} from '../shared/helpers/tags'
import React from 'react'
import PropTypes from 'prop-types'
import ExternalToolDialogModal from './ExternalToolDialog/Modal'
import ExternalToolDialogTray from './ExternalToolDialog/Tray'
import Alert from '@instructure/ui-alerts/lib/components/Alert'
import I18n from 'i18n!ExternalToolDialog'
import {send} from '../shared/rce/RceCommandShim'
import TinyMCEContentItem from 'tinymce_plugins/instructure_external_tools/TinyMCEContentItem'
import FlexItem from '@instructure/ui-layout/lib/components/Flex/FlexItem'
import processEditorContentItems from '../deep_linking/processors/processEditorContentItems'

const EMPTY_BUTTON = {
  height: 300,
  width: 400,
  name: ' '
}

const EMPTY_FORM = {
  url: '',
  selection: '',
  contents: ''
}

export default class ExternalToolDialog extends React.Component {
  static propTypes = {
    win: PropTypes.shape({
      addEventListener: PropTypes.func.isRequired,
      removeEventListener: PropTypes.func.isRequired,
      confirm: PropTypes.func.isRequired,
      height: PropTypes.number.isRequired,
      $: PropTypes.func.isRequired
    }).isRequired,
    editor: PropTypes.shape({
      id: PropTypes.string.isRequired,
      selection: PropTypes.shape({
        getContent: PropTypes.func.isRequired
      }),
      getContent: PropTypes.func.isRequired
    }).isRequired,
    contextAssetString: PropTypes.string.isRequired,
    iframeAllowances: PropTypes.string.isRequired,
    resourceSelectionUrl: PropTypes.string,
    deepLinkingOrigin: PropTypes.string
  }

  static defaultProps = {
    resourceSelectionUrl: null,
    deepLinkingOrigin: ''
  }

  state = {
    open: false,
    button: EMPTY_BUTTON,
    infoAlert: null,
    form: EMPTY_FORM
  }

  open(button) {
    const {win, editor, contextAssetString, resourceSelectionUrl} = this.props
    let url = replaceTags(resourceSelectionUrl, 'id', button.id)
    const selection = editor.selection.getContent() || ''
    const contents = editor.getContent() || ''
    if (url == null) {
      // if we don't have a url on the page, build one using the current context.
      // url should look like: /courses/2/external_tools/15/resoruce_selection?editor=1
      const asset = contextAssetString.split('_')
      url = `/${asset[0]}s/${asset[1]}/external_tools/${button.id}/resource_selection`
    }
    this.setState({open: true, button, form: {url, selection, contents}})
    win.addEventListener('beforeunload', this.handleBeforeUnload)
    win.addEventListener('message', this.handleDeepLinking)
    win.$(win).bind('externalContentReady', this.handleExternalContentReady)
  }

  close() {
    const {win} = this.props
    win.removeEventListener('beforeunload', this.handleBeforeUnload)
    win.removeEventListener('message', this.handleDeepLinking)
    win.$(win).unbind('externalContentReady')
    this.setState({open: false, form: EMPTY_FORM})
  }

  handleBeforeUnload = ev => (ev.returnValue = I18n.t('Changes you made may not be saved.'))

  handleExternalContentReady = (ev, data) => {
    const {editor, win} = this.props
    const contentItems = data.contentItems
    if (contentItems.length === 1 && contentItems[0]['@type'] === 'lti_replace') {
      const code = contentItems[0].text
      send(win.$(`#${editor.id}`), 'set_code', code)
    } else {
      for (let i = 0, len = contentItems.length; i < len; ++i) {
        const code = TinyMCEContentItem.fromJSON(contentItems[i]).codePayload
        send(win.$(`#${editor.id}`), 'insert_code', code)
      }
    }
    this.close()
  }

  handleDeepLinking = ev => {
    const {editor, deepLinkingOrigin} = this.props
    // Only accept messages from the same origin
    if (
      ev.origin === deepLinkingOrigin &&
      ev.data &&
      ev.data.messageType === 'LtiDeepLinkingResponse'
    ) {
      processEditorContentItems(ev, editor, this)
    }
  }

  handleClose = () => {
    const {win} = this.props
    const msg = I18n.t('Are you sure you want to cancel? Changes you made may not be saved.')
    if (win.confirm(msg)) {
      this.close()
    }
  }

  handleOpen = () => this.formRef.submit()

  handleRemove = () => {
    this.setState({button: EMPTY_BUTTON})
  }

  handleInfoAlertFocus = ev => this.setState({infoAlert: ev.target})

  handleInfoAlertBlur = () => this.setState({infoAlert: null})

  render() {
    const {open, button, form, infoAlert} = this.state
    const {iframeAllowances, win} = this.props
    const label = I18n.t('embed_from_external_tool', 'Embed content from External Tool')
    const frameHeight = Math.max(Math.min(win.height - 100, 550), 100)
    const Overlay = button.use_tray ? ExternalToolDialogTray : ExternalToolDialogModal
    return (
      <React.Fragment>
        <form
          ref={ref => (this.formRef = ref)}
          method="POST"
          action={form.url}
          target="external_tool_launch"
          style={{margin: 0}}
        >
          <input type="hidden" name="editor" value="1" />
          <input type="hidden" name="selection" value={form.selection} />
          <input type="hidden" name="editor_contents" value={form.contents} />
        </form>
        <Overlay
          open={open}
          label={label}
          onOpen={this.handleOpen}
          onClose={this.handleRemove}
          onCloseButton={this.handleClose}
          closeLabel={I18n.t('Close')}
          name={button.name}
        >
          <FlexItem>
            <div
              ref={ref => (this.beforeInfoAlertRef = ref)}
              tabIndex="0" // eslint-disable-line jsx-a11y/no-noninteractive-tabindex
              onFocus={this.handleInfoAlertFocus}
              onBlur={this.handleInfoAlertBlur}
              className={
                infoAlert && infoAlert === this.beforeInfoAlertRef ? '' : 'screenreader-only'
              }
            >
              <Alert margin="small">{I18n.t('The following content is partner provided')}</Alert>
            </div>
          </FlexItem>
          <iframe
            title={label}
            ref={ref => (this.iframeRef = ref)}
            name="external_tool_launch"
            src="/images/ajax-loader-medium-444.gif"
            id="external_tool_button_frame"
            style={{
              flexGrow: '1',
              flexShrink: '1',
              width: button.use_tray ? undefined : button.width || 800,
              height: button.use_tray ? undefined : button.height || frameHeight,
              border: '0'
            }}
            allow={iframeAllowances}
            borderstyle="0"
          />
          <FlexItem>
            <div
              ref={ref => (this.afterInfoAlertRef = ref)}
              tabIndex="0" // eslint-disable-line jsx-a11y/no-noninteractive-tabindex
              onFocus={this.handleInfoAlertFocus}
              onBlur={this.handleInfoAlertBlur}
              className={
                infoAlert && infoAlert === this.afterInfoAlertRef ? '' : 'screenreader-only'
              }
            >
              <Alert margin="small">{I18n.t('The preceding content is partner provided')}</Alert>
            </div>
          </FlexItem>
        </Overlay>
      </React.Fragment>
    )
  }
}
<|endoftext|>


<commit_before>/**
 * Created by kamalnrf
 */

'use strict';

const msg_me = require('../../msg-me');

const Connection = {
    estConnection (convo, payload, bot){
        console.log("Entered establishing connection");

        const question = "Enter the username you want to connect with.";

        const answer = (payload, chat) => {
            const userName = payload.message.text;
            const senderID = payload.sender.id;

            msg_me.isExiting(userName)
                .then(existense => {
                    //Checks if the usersname exists. if so finds the users fbID.
                    if (existense)
                        msg_me.findUser(userName)
                            .then(recieverID => {
                                msg_me.isOnline(recieverID)
                                    .then(isOnline => {
                                        //Checks whether the user is online.
                                        if (isOnline === 'true' || isOnline === true)
                                            msg_me.isConnected(recieverID)
                                                .then(conected => {
                                                    console.log(`Connected: ${conected}`);
                                                    //Checks if the user is not connected to anyone.
                                                    if (conected !== true || conected !== "true")
                                                        if (msg_me.connect(senderID, recieverID) === true) {
                                                            chat.say(`We have established connection between you and ${userName}.`);
                                                            bot.say(recieverID, `A connection has been established`);
                                                            convo.end();
                                                        } else
                                                            convo.say("Something went wrong try again");
                                                    else
                                                        convo.say("The user you want to talk to is already in a conversation");
                                                })
                                                .catch(error => console.log(error));
                                        else
                                            convo.say ("The user you are trying to ping is not available.")
                                                .then(() => convo.end());
                                    });
                            });
                    else {
                        convo.say("There is no such user, try entering again.")
                            .then(() => this.estConnection(convo, payload, bot));
                    }
                })
                .catch(error => console.log(error))
        };

        convo.ask(question, answer);
    }
};

module.exports = Connection;<commit_msg>patch<commit_after>/**
 * Created by kamalnrf
 */

'use strict';

const msg_me = require('../../msg-me');

const Connection = {
    estConnection (convo, payload, bot){
        console.log("Entered establishing connection");

        const question = "Enter the username you want to connect with.";

        const answer = (payload, chat) => {
            const userName = payload.message.text;
            const senderID = payload.sender.id;

            msg_me.isExiting(userName)
                .then(existense => {
                    //Checks if the usersname exists. if so finds the users fbID.
                    console.log(`User existence ${existense}`);
                    if (existense)
                        msg_me.findUser(userName)
                            .then(recieverID => {
                                console.log(`User recieverID ${recieverID}`);
                                msg_me.isOnline(recieverID)
                                    .then(isOnline => {
                                        console.log(`Is user online ${isOnline}`);
                                        //Checks whether the user is online.
                                        if (isOnline === 'true' || isOnline === true)
                                            msg_me.isConnected(recieverID)
                                                .then(conected => {
                                                    console.log(`Connected: ${conected}`);
                                                    //Checks if the user is not connected to anyone.
                                                    if (conected !== true || conected !== "true")
                                                        if (msg_me.connect(senderID, recieverID) === true) {
                                                            chat.say(`We have established connection between you and ${userName}.`);
                                                            bot.say(recieverID, `A connection has been established`);
                                                            convo.end();
                                                        } else
                                                            convo.say("Something went wrong try again");
                                                    else
                                                        convo.say("The user you want to talk to is already in a conversation");
                                                })
                                                .catch(error => console.log(error));
                                        else
                                            convo.say ("The user you are trying to ping is not available.")
                                                .then(() => convo.end());
                                    });
                            });
                    else {
                        convo.say("There is no such user, try entering again.")
                            .then(() => this.estConnection(convo, payload, bot));
                    }
                })
                .catch(error => console.log(error))
        };

        convo.ask(question, answer);
    }
};

module.exports = Connection;<|endoftext|>


<commit_before>var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
            t[p[i]] = s[p[i]];
    return t;
};
import React from 'react';
import PropTypes from 'prop-types';
import RcSelect, { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import warning from '../_util/warning';
const SelectPropTypes = {
    prefixCls: PropTypes.string,
    className: PropTypes.string,
    size: PropTypes.oneOf(['default', 'large', 'small']),
    combobox: PropTypes.bool,
    notFoundContent: PropTypes.any,
    showSearch: PropTypes.bool,
    optionLabelProp: PropTypes.string,
    transitionName: PropTypes.string,
    choiceTransitionName: PropTypes.string,
};
// => It is needless to export the declaration of below two inner components.
// export { Option, OptGroup };
export default class Select extends React.Component {
    constructor(props) {
        super(props);
        // by FEN 为了解决第一次点击的时候不出数据
        this.handlerfirstFocus = () => {
            if (this.state.isFirstFocus) {
                this.props.onFirstFocus && this.props.onFirstFocus();
                this.setState({
                    isFirstFocus: false
                });
            }
        };
        this.state = {
            isFirstFocus: true
        };
    }
    getLocale() {
        const { antLocale } = this.context;
        if (antLocale && antLocale.Select) {
            return antLocale.Select;
        }
        return {
            notFoundContent: '无匹配结果',
        };
    }
    render() {
        const _a = this.props, { prefixCls, className = '', size, mode,
        // @deprecated
        multiple, tags, combobox } = _a, restProps = __rest(_a, ["prefixCls", "className", "size", "mode", "multiple", "tags", "combobox"]);
        warning(!multiple && !tags && !combobox, '`Select[multiple|tags|combobox]` is deprecated, please use `Select[mode]` instead.');
        const cls = classNames({
            [`${prefixCls}-lg`]: size === 'large',
            [`${prefixCls}-sm`]: size === 'small',
        }, className);
        const locale = this.getLocale();
        let { notFoundContent = locale.notFoundContent, optionLabelProp } = this.props;
        const isCombobox = mode === 'combobox' || combobox;
        if (isCombobox) {
            notFoundContent = null;
            // children 带 dom 结构时，无法填入输入框
            optionLabelProp = optionLabelProp || 'value';
        }
        const modeConfig = {
            multiple: mode === 'multiple' || multiple,
            tags: mode === 'tags' || tags,
            combobox: isCombobox,
        };
        return (React.createElement(RcSelect, Object.assign({}, restProps, modeConfig, { prefixCls: prefixCls, className: cls, optionLabelProp: optionLabelProp || 'children', notFoundContent: notFoundContent, onFocus: this.handlerfirstFocus })));
    }
}
Select.Option = Option;
Select.OptGroup = OptGroup;
Select.defaultProps = {
    prefixCls: 'ant-select',
    showSearch: false,
    transitionName: 'slide-up',
    choiceTransitionName: 'zoom',
};
Select.propTypes = SelectPropTypes;
Select.contextTypes = {
    antLocale: PropTypes.object,
};
<commit_msg>// 为了解决第一次点击的时候不出数据 增加onFirstFocus事件时 覆盖了onFocus事件 现在不再覆盖onFocus事件<commit_after>var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
            t[p[i]] = s[p[i]];
    return t;
};
import React from 'react';
import PropTypes from 'prop-types';
import RcSelect, { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import warning from '../_util/warning';
const SelectPropTypes = {
    prefixCls: PropTypes.string,
    className: PropTypes.string,
    size: PropTypes.oneOf(['default', 'large', 'small']),
    combobox: PropTypes.bool,
    notFoundContent: PropTypes.any,
    showSearch: PropTypes.bool,
    optionLabelProp: PropTypes.string,
    transitionName: PropTypes.string,
    choiceTransitionName: PropTypes.string,
};
// => It is needless to export the declaration of below two inner components.
// export { Option, OptGroup };
export default class Select extends React.Component {
    constructor(props) {
        super(props);
        // by FEN 为了解决第一次点击的时候不出数据
        this.handlerfirstFocus = () => {
            if (this.state.isFirstFocus) {
                this.props.onFirstFocus && this.props.onFirstFocus();
                this.setState({
                    isFirstFocus: false
                });
            }
            this.props.onFocus && this.props.onFocus();
        };
        this.state = {
            isFirstFocus: true
        };
    }
    getLocale() {
        const { antLocale } = this.context;
        if (antLocale && antLocale.Select) {
            return antLocale.Select;
        }
        return {
            notFoundContent: '无匹配结果',
        };
    }
    render() {
        const _a = this.props, { prefixCls, className = '', size, mode,
        // @deprecated
        multiple, tags, combobox } = _a, restProps = __rest(_a, ["prefixCls", "className", "size", "mode", "multiple", "tags", "combobox"]);
        warning(!multiple && !tags && !combobox, '`Select[multiple|tags|combobox]` is deprecated, please use `Select[mode]` instead.');
        const cls = classNames({
            [`${prefixCls}-lg`]: size === 'large',
            [`${prefixCls}-sm`]: size === 'small',
        }, className);
        const locale = this.getLocale();
        let { notFoundContent = locale.notFoundContent, optionLabelProp } = this.props;
        const isCombobox = mode === 'combobox' || combobox;
        if (isCombobox) {
            notFoundContent = null;
            // children 带 dom 结构时，无法填入输入框
            optionLabelProp = optionLabelProp || 'value';
        }
        const modeConfig = {
            multiple: mode === 'multiple' || multiple,
            tags: mode === 'tags' || tags,
            combobox: isCombobox,
        };
        return (React.createElement(RcSelect, Object.assign({}, restProps, modeConfig, { prefixCls: prefixCls, className: cls, optionLabelProp: optionLabelProp || 'children', notFoundContent: notFoundContent, onFocus: this.handlerfirstFocus })));
    }
}
Select.Option = Option;
Select.OptGroup = OptGroup;
Select.defaultProps = {
    prefixCls: 'ant-select',
    showSearch: false,
    transitionName: 'slide-up',
    choiceTransitionName: 'zoom',
};
Select.propTypes = SelectPropTypes;
Select.contextTypes = {
    antLocale: PropTypes.object,
};
<|endoftext|>


<commit_before>import _ from 'lodash';
import Field from '../_classes/field/Field';

export default class CheckBoxComponent extends Field {
  static schema(...extend) {
    return Field.schema({
      type: 'checkbox',
      inputType: 'checkbox',
      label: 'Checkbox',
      key: 'checkbox',
      dataGridLabel: true,
      labelPosition: 'right',
      value: '',
      name: ''
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Checkbox',
      group: 'basic',
      icon: 'check-square',
      documentation: 'http://help.form.io/userguide/#checkbox',
      weight: 50,
      schema: CheckBoxComponent.schema()
    };
  }

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

  get defaultValue() {
    return this.component.name ? '' : (this.component.defaultValue || false).toString() === 'true';
  }

  get labelClass() {
    let className = '';
    if (this.isInputComponent
      && !this.options.inputsOnly
      && this.component.validate
      && this.component.validate.required) {
      className += ' field-required';
    }
    return `${className}`;
  }

  get hasSetValue() {
    return this.hasValue();
  }

  get inputInfo() {
    const info = super.elementInfo();
    info.type = 'input';
    info.changeEvent = 'click';
    info.attr.type = this.component.inputType || 'checkbox';
    info.attr.class = 'form-check-input';
    if (this.component.name) {
      info.attr.name = `data[${this.component.name}]`;
    }
    info.attr.value = this.component.value ? this.component.value : 0;
    info.label = this.t(this.component.label);
    info.labelClass = this.labelClass;
    return info;
  }

  get labelInfo() {
    return {
      hidden: true
    };
  }

  render() {
    return super.render(this.renderTemplate('checkbox', {
      input: this.inputInfo,
      checked: this.dataValue,
      tooltip: this.interpolate(this.t(this.component.tooltip) || '').replace(/(?:\r\n|\r|\n)/g, '
')
    }));
  }

  attach(element) {
    this.loadRefs(element, { input: 'multiple' });
    this.input = this.refs.input[0];
    if (this.refs.input) {
      this.addEventListener(this.input, this.inputInfo.changeEvent, () => this.updateValue(null, {
        modified: true
      }));
      this.addShortcut(this.input);
    }
    return super.attach(element);
  }

  detach(element) {
    if (element && this.input) {
      this.removeShortcut(this.input);
    }
  }

  get emptyValue() {
    return false;
  }

  isEmpty(value = this.dataValue) {
    return super.isEmpty(value) || value === false;
  }

  /**
   *
   * @param value {*}
   * @returns {*}
   */
  set dataValue(value) {
    const setValue = (super.dataValue = value);
    if (this.component.name) {
      _.set(this.data, this.component.key, setValue === this.component.value);
    }
    return setValue;
  }

  get dataValue() {
    const getValue = super.dataValue;
    if (this.component.name) {
      _.set(this.data, this.component.key, getValue === this.component.value);
    }
    return getValue;
  }

  get key() {
    return this.component.name ? this.component.name : super.key;
  }

  getValueAt(index) {
    if (this.component.name) {
      return this.refs.input[index].checked ? this.component.value : '';
    }
    return !!this.refs.input[index].checked;
  }

  getValue() {
    const value = super.getValue();
    if (this.component.name) {
      return value ? this.setCheckedState(value) : this.setCheckedState(this.dataValue);
    }
    else {
      return (value === '') ? this.dataValue : !!value;
    }
  }

  setCheckedState(value) {
    if (!this.input) {
      return;
    }
    if (this.component.name) {
      this.input.value = (value === this.component.value) ? this.component.value : 0;
      this.input.checked = (value === this.component.value) ? 1 : 0;
    }
    else if (value === 'on') {
      this.input.value = 1;
      this.input.checked = 1;
    }
    else if (value === 'off') {
      this.input.value = 0;
      this.input.checked = 0;
    }
    else if (value) {
      this.input.value = 1;
      this.input.checked = 1;
    }
    else {
      this.input.value = 0;
      this.input.checked = 0;
    }
    if (this.input.checked) {
      this.input.setAttribute('checked', true);
    }
    else {
      this.input.removeAttribute('checked');
    }
    return value;
  }

  setValue(value, flags) {
    flags = flags || {};
    if (this.setCheckedState(value) !== undefined) {
      return this.updateValue(value, flags);
    }
    return false;
  }

  getValueAsString(value) {
    return value ? 'Yes' : 'No';
  }
}
<commit_msg>Fix issue with hidden checkbox values not being updated correctly.<commit_after>import _ from 'lodash';
import Field from '../_classes/field/Field';

export default class CheckBoxComponent extends Field {
  static schema(...extend) {
    return Field.schema({
      type: 'checkbox',
      inputType: 'checkbox',
      label: 'Checkbox',
      key: 'checkbox',
      dataGridLabel: true,
      labelPosition: 'right',
      value: '',
      name: ''
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Checkbox',
      group: 'basic',
      icon: 'check-square',
      documentation: 'http://help.form.io/userguide/#checkbox',
      weight: 50,
      schema: CheckBoxComponent.schema()
    };
  }

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

  get defaultValue() {
    return this.component.name ? '' : (this.component.defaultValue || false).toString() === 'true';
  }

  get labelClass() {
    let className = '';
    if (this.isInputComponent
      && !this.options.inputsOnly
      && this.component.validate
      && this.component.validate.required) {
      className += ' field-required';
    }
    return `${className}`;
  }

  get hasSetValue() {
    return this.hasValue();
  }

  get inputInfo() {
    const info = super.elementInfo();
    info.type = 'input';
    info.changeEvent = 'click';
    info.attr.type = this.component.inputType || 'checkbox';
    info.attr.class = 'form-check-input';
    if (this.component.name) {
      info.attr.name = `data[${this.component.name}]`;
    }
    info.attr.value = this.component.value ? this.component.value : 0;
    info.label = this.t(this.component.label);
    info.labelClass = this.labelClass;
    return info;
  }

  get labelInfo() {
    return {
      hidden: true
    };
  }

  render() {
    return super.render(this.renderTemplate('checkbox', {
      input: this.inputInfo,
      checked: this.dataValue,
      tooltip: this.interpolate(this.t(this.component.tooltip) || '').replace(/(?:\r\n|\r|\n)/g, '
')
    }));
  }

  attach(element) {
    this.loadRefs(element, { input: 'multiple' });
    this.input = this.refs.input[0];
    if (this.refs.input) {
      this.addEventListener(this.input, this.inputInfo.changeEvent, () => this.updateValue(null, {
        modified: true
      }));
      this.addShortcut(this.input);
    }
    return super.attach(element);
  }

  detach(element) {
    if (element && this.input) {
      this.removeShortcut(this.input);
    }
  }

  get emptyValue() {
    return false;
  }

  isEmpty(value = this.dataValue) {
    return super.isEmpty(value) || value === false;
  }

  /**
   *
   * @param value {*}
   * @returns {*}
   */
  set dataValue(value) {
    const setValue = (super.dataValue = value);
    if (
      !this.key ||
      (!this.visible && this.component.clearOnHide && !this.rootPristine)
    ) {
      return setValue;
    }
    if (this.component.name) {
      _.set(this.data, this.component.key, setValue === this.component.value);
    }
    return setValue;
  }

  get dataValue() {
    const getValue = super.dataValue;
    if (this.component.name) {
      _.set(this.data, this.component.key, getValue === this.component.value);
    }
    return getValue;
  }

  get key() {
    return this.component.name ? this.component.name : super.key;
  }

  getValueAt(index) {
    if (this.component.name) {
      return this.refs.input[index].checked ? this.component.value : '';
    }
    return !!this.refs.input[index].checked;
  }

  getValue() {
    const value = super.getValue();
    if (this.component.name) {
      return value ? this.setCheckedState(value) : this.setCheckedState(this.dataValue);
    }
    else {
      return (value === '') ? this.dataValue : !!value;
    }
  }

  setCheckedState(value) {
    if (!this.input) {
      return;
    }
    if (this.component.name) {
      this.input.value = (value === this.component.value) ? this.component.value : 0;
      this.input.checked = (value === this.component.value) ? 1 : 0;
    }
    else if (value === 'on') {
      this.input.value = 1;
      this.input.checked = 1;
    }
    else if (value === 'off') {
      this.input.value = 0;
      this.input.checked = 0;
    }
    else if (value) {
      this.input.value = 1;
      this.input.checked = 1;
    }
    else {
      this.input.value = 0;
      this.input.checked = 0;
    }
    if (this.input.checked) {
      this.input.setAttribute('checked', true);
    }
    else {
      this.input.removeAttribute('checked');
    }
    return value;
  }

  setValue(value, flags) {
    flags = flags || {};
    if (this.setCheckedState(value) !== undefined) {
      return this.updateValue(value, flags);
    }
    return false;
  }

  getValueAsString(value) {
    return value ? 'Yes' : 'No';
  }
}
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import Menu from '@material-ui/core/Menu';
import Button from '@material-ui/core/Button';
import { MoreOptionsButton, CloseButton } from './IconButton';
import { getBrandDarkColor, getBrandDarkerColor } from '../../styles/colors';
// import AppButton from './AppButton';

class ActionMenu extends React.Component {
  state = {
    backgroundColor: getBrandDarkColor(),
    anchorEl: null,
  };

  handlePopupOpenClick = (event) => {
    if (event) {
      this.handlePopupOpen(event);
    } else {
      this.handlePopupClose(event);
    }
  }
  handlePopupOpen = (event) => {
    event.preventDefault(); // don't go anywhere on anchor click
    this.setState({ anchorEl: event.currentTarget });
  }
  handlePopupClose = () => {
    this.setState({ anchorEl: null });
  }
  handleMouseEnter = () => {
    this.setState({ backgroundColor: getBrandDarkerColor() });
  }
  handleMouseLeave = () => {
    this.setState({ backgroundColor: getBrandDarkColor() });
  }

  render() {
    const { color, openButton, closeButton, children, actionTextMsg } = this.props;
    const otherProps = {};
    const { anchorEl } = this.state;
    otherProps.backgroundColor = this.state.backgroundColor;
    let closeIconButton = (
      <CloseButton onClick={this.handlePopupClose} color={color} {...otherProps} aria-controls="action-menu" />
    );
    let openIconButton = (
      <MoreOptionsButton onClick={this.handlePopupOpenClick} color={color} {...otherProps} aria-haspopup="true" aria-owns="action-menu" aria-controls="action-menu" />
    );

    if (openButton) {
      openIconButton = open;
    }
    if (closeButton) {
      closeIconButton = close;
    }

    const icon = (this.state.anchorEl) ? closeIconButton : openIconButton;

    // support text or icon-driven menus
    let buttonContent;
    if (actionTextMsg) {
      buttonContent = (
        <Button
          className="action-menu-text"
          onClick={this.handlePopupOpenClick}
          aria-controls="action-menu"
          aria-haspopup="true"
          aria-owns="action-menu"
        >
          <FormattedMessage {...actionTextMsg} />
        </Button>
      );
    } else {
      buttonContent = icon;
    }

    return (

        {buttonContent}
        <Menu
          id="action-menu"
          anchorEl={anchorEl}
          onClose={this.handlePopupClose}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'left',
          }}
          transformOrigin={{
            vertical: 'bottom',
            horizontal: 'center',
          }}
          open={Boolean(this.state.anchorEl)}
          getContentAnchorEl={null}
        >
          {children}
        </Menu>

    );
  }
}
ActionMenu.propTypes = {
  onClick: PropTypes.func,
  topLevelButton: PropTypes.func,
  children: PropTypes.array,
  openButton: PropTypes.object,
  closeButton: PropTypes.object,
  tooltip: PropTypes.string,
  intl: PropTypes.object.isRequired,
  color: PropTypes.string,
  iconStyle: PropTypes.object,
  actionTextMsg: PropTypes.object,
};

export default injectIntl(ActionMenu);
<commit_msg>#1170 because we toggle btw the MoreOptionsButton and CloseButton, attach menu to parent parent element so it anchors properly<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import Menu from '@material-ui/core/Menu';
import Button from '@material-ui/core/Button';
import { MoreOptionsButton, CloseButton } from './IconButton';
import { getBrandDarkColor, getBrandDarkerColor } from '../../styles/colors';
// import AppButton from './AppButton';

class ActionMenu extends React.Component {
  state = {
    backgroundColor: getBrandDarkColor(),
    anchorEl: null,
  };

  handlePopupOpenClick = (event) => {
    if (event) {
      this.handlePopupOpen(event);
    } else {
      this.handlePopupClose(event);
    }
  }
  handlePopupOpen = (event) => {
    event.preventDefault(); // don't go anywhere on anchor click
    this.setState({ anchorEl: event.currentTarget.parentElement.parentElement });
  }
  handlePopupClose = () => {
    this.setState({ anchorEl: null });
  }
  handleMouseEnter = () => {
    this.setState({ backgroundColor: getBrandDarkerColor() });
  }
  handleMouseLeave = () => {
    this.setState({ backgroundColor: getBrandDarkColor() });
  }

  render() {
    const { color, openButton, closeButton, children, actionTextMsg } = this.props;
    const otherProps = {};
    const { anchorEl } = this.state;
    otherProps.backgroundColor = this.state.backgroundColor;
    let closeIconButton = (
      <CloseButton onClick={this.handlePopupClose} color={color} {...otherProps} aria-controls="action-menu" />
    );
    let openIconButton = (
      <MoreOptionsButton
        className="action-menu-icon"
        onClick={this.handlePopupOpenClick}
        aria-haspopup="true"
        aria-owns="action-menu"
        aria-controls="action-menu"
      />
    );

    if (openButton) {
      openIconButton = open;
    }
    if (closeButton) {
      closeIconButton = close;
    }

    const icon = (this.state.anchorEl) ? closeIconButton : openIconButton;

    // support text or icon-driven menus
    let buttonContent;
    if (actionTextMsg) {
      buttonContent = (
        <Button
          className="action-menu-text"
          onClick={this.handlePopupOpenClick}
          aria-controls="action-menu"
          aria-haspopup="true"
          aria-owns="action-menu"
        >
          <FormattedMessage {...actionTextMsg} />
        </Button>
      );
    } else {
      buttonContent = icon;
    }

    return (

        {buttonContent}
        <Menu
          id="action-menu"
          anchorEl={anchorEl}
          onClose={this.handlePopupClose}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'left',
          }}
          transformOrigin={{
            vertical: 'bottom',
            horizontal: 'center',
          }}
          open={Boolean(this.state.anchorEl)}
          getContentAnchorEl={null}
        >
          {children}
        </Menu>

    );
  }
}
ActionMenu.propTypes = {
  onClick: PropTypes.func,
  topLevelButton: PropTypes.func,
  children: PropTypes.array,
  openButton: PropTypes.object,
  closeButton: PropTypes.object,
  tooltip: PropTypes.string,
  intl: PropTypes.object.isRequired,
  color: PropTypes.string,
  iconStyle: PropTypes.object,
  actionTextMsg: PropTypes.object,
};

export default injectIntl(ActionMenu);
<|endoftext|>


<commit_before>import { createNumberMask } from 'text-mask-addons';
import { maskInput } from 'vanilla-text-mask';
import _ from 'lodash';
import { getCurrencyAffixes } from '../../utils/utils';
import NumberComponent from '../number/Number';

export default class CurrencyComponent extends NumberComponent {
  static schema(...extend) {
    return NumberComponent.schema({
      type: 'currency',
      label: 'Currency',
      key: 'currency'
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Currency',
      group: 'advanced',
      icon: 'usd',
      documentation: 'http://help.form.io/userguide/#currency',
      weight: 70,
      schema: CurrencyComponent.schema()
    };
  }

  constructor(component, options, data) {
    // Currency should default to have a delimiter unless otherwise specified.
    if (component && !component.hasOwnProperty('delimiter')) {
      component.delimiter = true;
    }
    super(component, options, data);
  }

  /**
   * Creates the number mask for currency numbers.
   *
   * @return {*}
   */
  createNumberMask() {
    const decimalLimit = _.get(this.component, 'decimalLimit', 2);
    const affixes = getCurrencyAffixes({
      currency: this.component.currency,
      decimalLimit: decimalLimit,
      decimalSeparator: this.decimalSeparator,
      lang: this.options.language
    });
    this.prefix = this.options.prefix || affixes.prefix;
    this.suffix = this.options.suffix || affixes.suffix;
    return createNumberMask({
      prefix: this.prefix,
      suffix: this.suffix,
      thousandsSeparatorSymbol: _.get(this.component, 'thousandsSeparator', this.delimiter),
      decimalSymbol: _.get(this.component, 'decimalSymbol', this.decimalSeparator),
      decimalLimit: decimalLimit,
      allowNegative: _.get(this.component, 'allowNegative', true),
      allowDecimal: _.get(this.component, 'allowDecimal', true)
    });
  }

  setInputMask(input) {
    const affixes = getCurrencyAffixes({
      currency: this.component.currency,
      decimalSeparator: this.decimalSeparator,
      lang: this.options.language,
    });
    let numberPattern = `\\${affixes.prefix}[0-9`;
    numberPattern += this.decimalSeparator || '';
    numberPattern += this.delimiter || '';
    numberPattern += ']*';
    input.setAttribute('pattern', numberPattern);
    input.mask = maskInput({
      inputElement: input,
      mask: this.numberMask || '',
    });
    input.mask.destroy();

    const inputHandler = ({ target: { value } }) => {
      input.mask.textMaskInputElement.update(value);
      if (value === '.' && input.prevValue) {
        const caretPosition = input.value.length - 1;
        input.setSelectionRange(caretPosition, caretPosition);
      }
      input.prevValue = input.value;
    };
    input.mask.textMaskInputElement.update(input.value);
    // Delay to allow mask to update first.
    setTimeout(() => {
      input.prevValue = input.value;
    });
    input.addEventListener('input', inputHandler);
  }

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

  parseNumber(value) {
    return super.parseNumber(this.stripPrefixSuffix(value));
  }

  parseValue(value) {
    return super.parseValue(this.stripPrefixSuffix(value));
  }

  addZerosAndFormatValue(value) {
   if (!value && value !== 0) return;

    const decimalLimit = _.get(this.component, 'decimalLimit', 2);

    let integerPart;
    let decimalPart = '';
    let decimalPartNumbers = [];
    const negativeValueSymbol = '-';
    const hasPrefix = this.prefix ? value.includes(this.prefix) : false;
    const hasSuffix = this.suffix ? value.includes(this.suffix) : false;
    const isNegative = value.includes(negativeValueSymbol) || false;

    value = this.stripPrefixSuffix(isNegative ? value.replace(negativeValueSymbol,'') : value);

    if (value.includes(this.decimalSeparator)) {
      [integerPart, decimalPart] = value.split(this.decimalSeparator);
      decimalPartNumbers =[...decimalPart.split('')] ;
    }
    else {
      integerPart = value;
    }

    if (decimalPart.length < decimalLimit) {
      while (decimalPartNumbers.length < decimalLimit) {
        decimalPartNumbers.push('0');
      }
    }

    const formattedValue = `${isNegative ? negativeValueSymbol:''}${hasPrefix ? this.prefix : ''}${integerPart}${this.decimalSeparator}${decimalPartNumbers.join('')}${hasSuffix ? this.suffix : ''}`;

    return super.formatValue(formattedValue);
  }

  getValueAsString(value, options) {
    const stringValue = super.getValueAsString(value, options);

    // eslint-disable-next-line eqeqeq
    if (value || value == '0') {
      return this.addZerosAndFormatValue(stringValue);
    }

    return stringValue;
  }

  formatValue(value) {
    if (value || value === '0') {
      return this.addZerosAndFormatValue(value);
    }

    return super.formatValue(value);
  }

  stripPrefixSuffix(value) {
    if (typeof value === 'string') {
      try {
        const hasPrefix = this.prefix ? value.includes(this.prefix) : false;
        const hasSuffix = this.suffix ? value.includes(this.suffix) : false;
        const hasDelimiter = value.includes(this.delimiter);
        const hasDecimalSeparator = value.includes(this.decimalSeparator);

        if (this.prefix) {
          value = value.replace(this.prefix, '');
        }
        if (this.suffix) {
          value = value.replace(this.suffix, '');
        }
        //when we enter $ in the field using dashboard, it contains '_' that is NaN
        if ((hasPrefix || hasSuffix) && !hasDelimiter && !hasDecimalSeparator && (Number.isNaN(+value) || !value)) {
          value ='0';
        }
      }
      catch (err) {
        // If value doesn't have a replace method, continue on as before.
      }
    }
    return value;
  }

  addFocusBlurEvents(element) {
    super.addFocusBlurEvents(element);

    this.addEventListener(element, 'blur', () => {
      element.value = this.getValueAsString(this.addZerosAndFormatValue(this.parseValue(element.value)));
    });
  }
}
<commit_msg>Use afterUpdate callback<commit_after>import { createNumberMask } from 'text-mask-addons';
import { maskInput } from 'vanilla-text-mask';
import _ from 'lodash';
import { getCurrencyAffixes } from '../../utils/utils';
import NumberComponent from '../number/Number';

export default class CurrencyComponent extends NumberComponent {
  static schema(...extend) {
    return NumberComponent.schema({
      type: 'currency',
      label: 'Currency',
      key: 'currency'
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Currency',
      group: 'advanced',
      icon: 'usd',
      documentation: 'http://help.form.io/userguide/#currency',
      weight: 70,
      schema: CurrencyComponent.schema()
    };
  }

  constructor(component, options, data) {
    // Currency should default to have a delimiter unless otherwise specified.
    if (component && !component.hasOwnProperty('delimiter')) {
      component.delimiter = true;
    }
    super(component, options, data);
  }

  /**
   * Creates the number mask for currency numbers.
   *
   * @return {*}
   */
  createNumberMask() {
    const decimalLimit = _.get(this.component, 'decimalLimit', 2);
    const affixes = getCurrencyAffixes({
      currency: this.component.currency,
      decimalLimit: decimalLimit,
      decimalSeparator: this.decimalSeparator,
      lang: this.options.language
    });
    this.prefix = this.options.prefix || affixes.prefix;
    this.suffix = this.options.suffix || affixes.suffix;
    return createNumberMask({
      prefix: this.prefix,
      suffix: this.suffix,
      thousandsSeparatorSymbol: _.get(this.component, 'thousandsSeparator', this.delimiter),
      decimalSymbol: _.get(this.component, 'decimalSymbol', this.decimalSeparator),
      decimalLimit: decimalLimit,
      allowNegative: _.get(this.component, 'allowNegative', true),
      allowDecimal: _.get(this.component, 'allowDecimal', true)
    });
  }

  setInputMask(input) {
    const affixes = getCurrencyAffixes({
      currency: this.component.currency,
      decimalSeparator: this.decimalSeparator,
      lang: this.options.language,
    });
    let numberPattern = `\\${affixes.prefix}[0-9`;
    numberPattern += this.decimalSeparator || '';
    numberPattern += this.delimiter || '';
    numberPattern += ']*';
    input.setAttribute('pattern', numberPattern);
    input.mask = maskInput({
      inputElement: input,
      mask: this.numberMask || '',
      afterUpdate: (value) => {
        if (value === '.' && input.prevValue) {
          const caretPosition = input.value.length - 1;
          input.setSelectionRange(caretPosition, caretPosition);
        }
        input.prevValue = value;
      }
    });

    input.mask.textMaskInputElement.update(input.value);
    // Delay to allow mask to update first.
    setTimeout(() => {
      input.prevValue = input.value;
    });
  }

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

  parseNumber(value) {
    return super.parseNumber(this.stripPrefixSuffix(value));
  }

  parseValue(value) {
    return super.parseValue(this.stripPrefixSuffix(value));
  }

  addZerosAndFormatValue(value) {
   if (!value && value !== 0) return;

    const decimalLimit = _.get(this.component, 'decimalLimit', 2);

    let integerPart;
    let decimalPart = '';
    let decimalPartNumbers = [];
    const negativeValueSymbol = '-';
    const hasPrefix = this.prefix ? value.includes(this.prefix) : false;
    const hasSuffix = this.suffix ? value.includes(this.suffix) : false;
    const isNegative = value.includes(negativeValueSymbol) || false;

    value = this.stripPrefixSuffix(isNegative ? value.replace(negativeValueSymbol,'') : value);

    if (value.includes(this.decimalSeparator)) {
      [integerPart, decimalPart] = value.split(this.decimalSeparator);
      decimalPartNumbers =[...decimalPart.split('')] ;
    }
    else {
      integerPart = value;
    }

    if (decimalPart.length < decimalLimit) {
      while (decimalPartNumbers.length < decimalLimit) {
        decimalPartNumbers.push('0');
      }
    }

    const formattedValue = `${isNegative ? negativeValueSymbol:''}${hasPrefix ? this.prefix : ''}${integerPart}${this.decimalSeparator}${decimalPartNumbers.join('')}${hasSuffix ? this.suffix : ''}`;

    return super.formatValue(formattedValue);
  }

  getValueAsString(value, options) {
    const stringValue = super.getValueAsString(value, options);

    // eslint-disable-next-line eqeqeq
    if (value || value == '0') {
      return this.addZerosAndFormatValue(stringValue);
    }

    return stringValue;
  }

  formatValue(value) {
    if (value || value === '0') {
      return this.addZerosAndFormatValue(value);
    }

    return super.formatValue(value);
  }

  stripPrefixSuffix(value) {
    if (typeof value === 'string') {
      try {
        const hasPrefix = this.prefix ? value.includes(this.prefix) : false;
        const hasSuffix = this.suffix ? value.includes(this.suffix) : false;
        const hasDelimiter = value.includes(this.delimiter);
        const hasDecimalSeparator = value.includes(this.decimalSeparator);

        if (this.prefix) {
          value = value.replace(this.prefix, '');
        }
        if (this.suffix) {
          value = value.replace(this.suffix, '');
        }
        //when we enter $ in the field using dashboard, it contains '_' that is NaN
        if ((hasPrefix || hasSuffix) && !hasDelimiter && !hasDecimalSeparator && (Number.isNaN(+value) || !value)) {
          value ='0';
        }
      }
      catch (err) {
        // If value doesn't have a replace method, continue on as before.
      }
    }
    return value;
  }

  addFocusBlurEvents(element) {
    super.addFocusBlurEvents(element);

    this.addEventListener(element, 'blur', () => {
      element.value = this.getValueAsString(this.addZerosAndFormatValue(this.parseValue(element.value)));
    });
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import Reflux from 'reflux';
import Codemirror from 'react-codemirror';

import CMInstance from 'codemirror';
import CT3000 from '../../config/codemirrorCustomMode';

import 'codemirror/addon/mode/simple';
import 'codemirror/addon/selection/active-line';

import ObjectActions from '../../actions/object';
import ObjectStore from '../../stores/object';

export default class EditorPane extends React.Component {

  constructor(props) {
    super(props);

    this.updateCode = this.updateCode.bind(this);
    this.parseUntilLine = this.parseUntilLine.bind(this);

    this.lineInterval = null;
    this.lineTimeoutDuration = 500;

    this.state = {
      code: '',
      mode: '',
      languageInitiated: false
    };
  }

  componentDidMount() {
    this.unsubscribe = ObjectStore.listen((data) => {
      this.onUpdate(data);
    });

    this.cm = this.refs.editor.getCodeMirror();
    this.setLineInterval();

    // Example 'syntax error':
    // const doc = this.cm.getDoc();
    // doc.addLineClass(0,"wrap","syntax-error");
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  onUpdate(data) {
    if(!this.state.languageInitiated) {
      this.initLanguage();
    }
  }

  initLanguage() {
    let availableObjects = ObjectStore.getAvailableObjects();
    let availableValues = ObjectStore.getAvailableValues();

    var language = new CT3000();
    CMInstance.defineSimpleMode('ct-3000', language.getMode(availableObjects, availableValues));
    this.setState({
      mode: 'ct-3000',
      languageInitiated: true
    });
  }

  updateCode(newCode) {
    this.setState({
      code: newCode
    });
  }

  setLineInterval() {
    this.clearLineInterval();
    this.lineInterval = setInterval(this.parseUntilLine, this.lineTimeoutDuration);
  }

  clearLineInterval() {
    clearInterval(this.lineInterval);
  }

  parseUntilLine() {
    const currentLineNr = this.cm.getCursor().line;
    this.cm.eachLine(0, currentLineNr, (handle) => {
      this.parseLine(this.cm.getLineNumber(handle));
    });

    this.parseLine(currentLineNr, true);
  }

  parseLine(lineNr, assign = false) {
    const lineContent = this.cm.getLine(lineNr);

    ObjectActions.parse(lineContent, assign);
  }

  render() {
    var options = {
      lineNumbers: true,
      lineWrapping: true,
      indentUnit: 2,
      tabSize: 2,
      theme: 'monokai',
      styleActiveLine: true,
      mode: this.state.mode
    };

    return (

        <Codemirror ref="editor" value={ this.state.code } onChange={ this.updateCode } options={ options } />

    );
  }

}
<commit_msg>Add timeouts to sending lines to parser.<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import Reflux from 'reflux';
import Codemirror from 'react-codemirror';

import CMInstance from 'codemirror';
import CT3000 from '../../config/codemirrorCustomMode';

import 'codemirror/addon/mode/simple';
import 'codemirror/addon/selection/active-line';

import ObjectActions from '../../actions/object';
import ObjectStore from '../../stores/object';

export default class EditorPane extends React.Component {

  constructor(props) {
    super(props);

    this.updateCode = this.updateCode.bind(this);
    this.parseUntilLine = this.parseUntilLine.bind(this);

    this.lineInterval = null;
    this.lineTimeoutDuration = 500;

    this.state = {
      code: '',
      mode: '',
      languageInitiated: false
    };
  }

  componentDidMount() {
    this.unsubscribe = ObjectStore.listen((data) => {
      this.onUpdate(data);
    });

    this.cm = this.refs.editor.getCodeMirror();
    this.setLineInterval();

    // Example 'syntax error':
    // const doc = this.cm.getDoc();
    // doc.addLineClass(0,"wrap","syntax-error");
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  onUpdate(data) {
    if(!this.state.languageInitiated) {
      this.initLanguage();
    }
  }

  initLanguage() {
    let availableObjects = ObjectStore.getAvailableObjects();
    let availableValues = ObjectStore.getAvailableValues();

    var language = new CT3000();
    CMInstance.defineSimpleMode('ct-3000', language.getMode(availableObjects, availableValues));
    this.setState({
      mode: 'ct-3000',
      languageInitiated: true
    });
  }

  updateCode(newCode) {
    this.setState({
      code: newCode
    });
  }

  setLineInterval() {
    this.clearLineInterval();
    this.lineInterval = setInterval(this.parseUntilLine, this.lineTimeoutDuration);
  }

  clearLineInterval() {
    clearInterval(this.lineInterval);
  }

  parseUntilLine() {
    const currentLineNr = this.cm.getCursor().line;

    this.cm.eachLine(0, currentLineNr, (handle) => {
      const lineNr = this.cm.getLineNumber(handle);
      setTimeout(() => {
        this.parseLine(this.cm.getLineNumber(handle));
      }, 10 * lineNr);
    });

    setTimeout(() => {
      this.parseLine(currentLineNr, true);
    }, 10 * currentLineNr);
  }

  parseLine(lineNr, assign = false) {
    const lineContent = this.cm.getLine(lineNr);
    ObjectActions.parse(lineContent, assign);
  }

  render() {
    var options = {
      lineNumbers: true,
      lineWrapping: true,
      indentUnit: 2,
      tabSize: 2,
      theme: 'monokai',
      styleActiveLine: true,
      mode: this.state.mode
    };

    return (

        <Codemirror ref="editor" value={ this.state.code } onChange={ this.updateCode } options={ options } />

    );
  }

}
<|endoftext|>


<commit_before>var url = require('url')
var Cache = require('magazine')
var merge = require('./merge')

var Evaluator = require('prolific.evaluator')

var coalesce = require('extant')

function Processor (parameters, next, options) {
    options || (options = {})
    this._timeout = coalesce(options.timeout, 30000)
    this._delay = coalesce(options.delay, 5000)
    this._pivot = Evaluator.create(parameters.pivot)
    this._end = Evaluator.create(parameters.end)
    this._calculations = parameters.calculate.forEach(function (calculate) {
        return Evaluator.create(calculate)
    })
    this._building = new Cache().createMagazine()
    this._sending = new Cache().createMagazine()
    this._next = next
}

Processor.prototype.open = function (callback) { callback() }

Processor.prototype.process = function (entry) {
    this._maybeSend(this._sending, Date.now() - this._delay)
    this._maybeSend(this._building, Date.now() - this._timeout)

    var pivot = this._pivot.call(null, entry)
    if (pivot == null) {
        this._next.process(entry)
    } else {
        var got = this._sending.get(pivot)
        if (got == null) {
            got = this._building.get(pivot, { entry: {} })
        }
        merge(got.entry, entry)
        if (this._end.call(null, got.entry)) {
            this._sending.put(pivot, got)
            this._building.remove(pivot)
        }
    }
}

Processor.prototype._maybeSend = function (magazine, before) {
    var iterator = magazine.iterator()
    while (!iterator.end && iterator.when < before) {
        var entry = magazine.get(iterator.key)
        this._next.process(entry.entry)
        magazine.remove(iterator.key)
        iterator.previous()
    }
}

Processor.prototype.close = function (callback) { callback() }

module.exports = Processor
<commit_msg>Remove unused list of calculations.<commit_after>var url = require('url')
var Cache = require('magazine')
var merge = require('./merge')

var Evaluator = require('prolific.evaluator')

var coalesce = require('extant')

function Processor (parameters, next, options) {
    options || (options = {})
    this._timeout = coalesce(options.timeout, 30000)
    this._delay = coalesce(options.delay, 5000)
    this._pivot = Evaluator.create(parameters.pivot)
    this._end = Evaluator.create(parameters.end)
    this._building = new Cache().createMagazine()
    this._sending = new Cache().createMagazine()
    this._next = next
}

Processor.prototype.open = function (callback) { callback() }

Processor.prototype.process = function (entry) {
    this._maybeSend(this._sending, Date.now() - this._delay)
    this._maybeSend(this._building, Date.now() - this._timeout)

    var pivot = this._pivot.call(null, entry)
    if (pivot == null) {
        this._next.process(entry)
    } else {
        var got = this._sending.get(pivot)
        if (got == null) {
            got = this._building.get(pivot, { entry: {} })
        }
        merge(got.entry, entry)
        if (this._end.call(null, got.entry)) {
            this._sending.put(pivot, got)
            this._building.remove(pivot)
        }
    }
}

Processor.prototype._maybeSend = function (magazine, before) {
    var iterator = magazine.iterator()
    while (!iterator.end && iterator.when < before) {
        var entry = magazine.get(iterator.key)
        this._next.process(entry.entry)
        magazine.remove(iterator.key)
        iterator.previous()
    }
}

Processor.prototype.close = function (callback) { callback() }

module.exports = Processor
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import theme from './theme.css';
import cx from 'classnames';
import omit from 'lodash.omit';
import Box, { omitBoxProps, pickBoxProps } from '../box';
import { TextBody, TextDisplay, TextSmall } from '../typography';

class RadioButton extends PureComponent {
  handleToggle = event => {
    const { disabled, checked, onChange } = this.props;

    if (event.pageX !== 0 && event.pageY !== 0) {
      this.blur();
    }

    if (!disabled && onChange) {
      onChange(!checked, event);
    }
  };

  splitProps(props) {
    const availableBoxProps = [
      'margin',
      'marginVertical',
      'marginHorizontal',
      'marginBottom',
      'marginLeft',
      'marginRight',
      'marginTop',
      'padding',
      'paddingHorizontal',
      'paddingVertical',
      'paddingBottom',
      'paddingLeft',
      'paddingRight',
      'paddingTop',
    ];

    const boxProps = {};
    const inputProps = {};

    Object.keys(props).forEach(key => {
      const value = props[key];

      if (availableBoxProps.includes(key)) {
        boxProps[key] = value;
      } else {
        inputProps[key] = value;
      }
    });

    return { boxProps, inputProps };
  }

  blur() {
    if (this.inputNode) {
      this.inputNode.blur();
    }
  }

  focus() {
    if (this.inputNode) {
      this.inputNode.focus();
    }
  }

  render() {
    const { checked, disabled, className, size, label, children, onMouseEnter, onMouseLeave, ...others } = this.props;
    const TextElement = size === 'small' ? TextSmall : size === 'medium' ? TextBody : TextDisplay;

    const restProps = omit(others, ['onChange']);
    const boxProps = pickBoxProps(restProps);
    const inputProps = omitBoxProps(restProps);

    const classNames = cx(
      theme['radiobutton'],
      theme[`is-${size}`],
      {
        [theme['is-checked']]: checked,
        [theme['is-disabled']]: disabled,
      },
      className,
    );

    return (
      <Box
        element="label"
        data-teamleader-ui="radiobutton"
        className={classNames}
        onMouseEnter={onMouseEnter}
        onMouseLeave={onMouseLeave}
        {...boxProps}
      >
        <input
          className={theme['input']}
          type="radio"
          checked={checked}
          disabled={disabled}
          onClick={this.handleToggle}
          readOnly
          ref={node => {
            this.inputNode = node;
          }}
          {...inputProps}
        />

        {(label || children) && (

            {label && (
              <TextElement element="span" color={disabled ? 'neutral' : 'teal'} tint="darkest">
                {label}
              </TextElement>
            )}
            {children}

        )}
      </Box>
    );
  }
}

RadioButton.propTypes = {
  checked: PropTypes.bool,
  children: PropTypes.node,
  disabled: PropTypes.bool,
  name: PropTypes.string,
  className: PropTypes.string,
  label: PropTypes.string,
  onChange: PropTypes.func,
  onMouseEnter: PropTypes.func,
  onMouseLeave: PropTypes.func,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
};

RadioButton.defaultProps = {
  checked: false,
  disabled: false,
  size: 'medium',
};

export default RadioButton;
<commit_msg>Remove the obsolete 'splitProps' function<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import theme from './theme.css';
import cx from 'classnames';
import omit from 'lodash.omit';
import Box, { omitBoxProps, pickBoxProps } from '../box';
import { TextBody, TextDisplay, TextSmall } from '../typography';

class RadioButton extends PureComponent {
  handleToggle = event => {
    const { disabled, checked, onChange } = this.props;

    if (event.pageX !== 0 && event.pageY !== 0) {
      this.blur();
    }

    if (!disabled && onChange) {
      onChange(!checked, event);
    }
  };

  blur() {
    if (this.inputNode) {
      this.inputNode.blur();
    }
  }

  focus() {
    if (this.inputNode) {
      this.inputNode.focus();
    }
  }

  render() {
    const { checked, disabled, className, size, label, children, onMouseEnter, onMouseLeave, ...others } = this.props;
    const TextElement = size === 'small' ? TextSmall : size === 'medium' ? TextBody : TextDisplay;

    const restProps = omit(others, ['onChange']);
    const boxProps = pickBoxProps(restProps);
    const inputProps = omitBoxProps(restProps);

    const classNames = cx(
      theme['radiobutton'],
      theme[`is-${size}`],
      {
        [theme['is-checked']]: checked,
        [theme['is-disabled']]: disabled,
      },
      className,
    );

    return (
      <Box
        element="label"
        data-teamleader-ui="radiobutton"
        className={classNames}
        onMouseEnter={onMouseEnter}
        onMouseLeave={onMouseLeave}
        {...boxProps}
      >
        <input
          className={theme['input']}
          type="radio"
          checked={checked}
          disabled={disabled}
          onClick={this.handleToggle}
          readOnly
          ref={node => {
            this.inputNode = node;
          }}
          {...inputProps}
        />

        {(label || children) && (

            {label && (
              <TextElement element="span" color={disabled ? 'neutral' : 'teal'} tint="darkest">
                {label}
              </TextElement>
            )}
            {children}

        )}
      </Box>
    );
  }
}

RadioButton.propTypes = {
  checked: PropTypes.bool,
  children: PropTypes.node,
  disabled: PropTypes.bool,
  name: PropTypes.string,
  className: PropTypes.string,
  label: PropTypes.string,
  onChange: PropTypes.func,
  onMouseEnter: PropTypes.func,
  onMouseLeave: PropTypes.func,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
};

RadioButton.defaultProps = {
  checked: false,
  disabled: false,
  size: 'medium',
};

export default RadioButton;
<|endoftext|>