<commit_before>import React, { PropTypes, Component } from 'react';
import styles from './styles.scss';
import RemoveButton from '../RemoveButton';
import ContactDropdownList from '../ContactDropdownList';

function SelectedRecipientItem(props) {
  const className = props.phoneNumber.length > 5 ? styles.blue : null;
  return (

      {props.name}
      <RemoveButton
        className={styles.removeReceiver}
        onClick={props.onRemove}
        visibility
      />

  );
}

SelectedRecipientItem.propTypes = {
  name: PropTypes.string.isRequired,
  phoneNumber: PropTypes.string.isRequired,
  onRemove: PropTypes.func.isRequired,
};

function SelectedRecipients(props) {
  const items = props.items;
  if (items.length < 1) {
    return null;
  }
  return (

      {
        items.map(item => (
          <SelectedRecipientItem
            key={item.phoneNumber}
            name={item.name}
            phoneNumber={item.phoneNumber}
            onRemove={() => props.removeFromRecipients(item.phoneNumber)}
          />
        ))
      }

  );
}

SelectedRecipients.propTypes = {
  removeFromRecipients: PropTypes.func.isRequired,
  items: React.PropTypes.arrayOf(PropTypes.shape({
    phoneNumber: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
  })).isRequired,
};

class RecipientsInput extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isFocusOnInput: false,
      selectedContactIndex: 0,
      scrollDirection: null,
      currentValue: props.value.replace(',', ''),
    };

    this.onReceiversInputFocus = () => {
      this.setState({
        isFocusOnInput: true,
      });
    };

    this.onReceiversInputBlur = () => {
      this.setState({
        isFocusOnInput: false,
      });
    };

    this.setSelectedIndex = (index) => {
      this.setState({
        selectedContactIndex: index,
        scrollDirection: null,
      });
    };
    this.scrollOperation = (direction) => {
      if (direction === 'ArrowDown' || direction === 'ArrowUp') {
        this.setState({
          scrollDirection: direction,
        });
      }
    };
    this.addSelectedContactIndex = () => {
      const length = this.props.searchContactList.length;
      if (this.state.selectedContactIndex >= (length - 1)) {
        this.setState({
          selectedContactIndex: length - 1,
        });
      } else {
        this.setState(preState => ({
          selectedContactIndex: (preState.selectedContactIndex + 1),
        }));
      }
    };

    this.reduceSelectedContactIndex = () => {
      if (this.state.selectedContactIndex > 0) {
        this.setState(preState => ({
          selectedContactIndex: (preState.selectedContactIndex - 1),
        }));
      } else {
        this.setState({
          selectedContactIndex: 0,
        });
      }
    };

    this.handleHotKey = (e) => {
      if (this.state.isFocusOnInput && this.props.value.length >= 3) {
        if (e.key === 'ArrowUp') {
          this.reduceSelectedContactIndex();
          this.scrollOperation(e.key);
        } else if (e.key === 'ArrowDown') {
          this.addSelectedContactIndex();
          this.scrollOperation(e.key);
        }
      } else {
        this.setState({
          selectedContactIndex: 0,
        });
      }
      if (e.key === ',' || e.key === ';' || e.key === 'Enter') {
        e.preventDefault();
        if (this.props.value.length === 0) {
          return;
        }
        const relatedContactList = this.props.value.length >= 3 ?
          this.props.searchContactList : [];
        const currentSelected
          = relatedContactList[this.state.selectedContactIndex];
        if (currentSelected) {
          this.props.addToRecipients({
            name: currentSelected.name,
            phoneNumber: currentSelected.phoneNumber,
          });
        } else {
          this.props.addToRecipients({
            name: this.props.value.replace(',', ''),
            phoneNumber: this.props.value.replace(',', ''),
          });
          this.props.onClean();
        }
        this.props.onClean();
      }
    };
  }
  componentWillReceiveProps(newProps) {
    this.setState({
      currentValue: newProps.value.replace(',', '')
    });
    if (newProps.value &&
        newProps.value !== this.props.value &&
        this.props.value[this.props.value.length - 1] === ',') {
      this.setState({
        isFocusOnInput: true,
      });
      this.props.addToRecipients({
        name: this.props.value.replace(',', ''),
        phoneNumber: this.props.value.replace(',', ''),
      }, false);
    }
  }
  render() {
    const relatedContactList = this.props.value.length >= 3 ?
      this.props.searchContactList : [];
    const label = this.props.label ?
      (
        {this.props.label}
      ) : null;
    return (

        {label}

          <SelectedRecipients
            items={this.props.recipients}
            removeFromRecipients={this.props.removeFromRecipients}
          />

            <input
              name="receiver"
              value={this.state.currentValue}
              onChange={this.props.onChange}
              onKeyUp={this.props.onKeyUp}
              onKeyDown={this.props.onKeyDown}
              className={styles.numberInput}
              maxLength={30}
              onFocus={this.onReceiversInputFocus}
              onBlur={this.onReceiversInputBlur}
              placeholder={this.props.placeholder}
              autoComplete="off"
            />

          <RemoveButton
            className={styles.removeButton}
            onClick={this.props.onClean}
            visibility={
              this.props.value.length > 0 &&
              this.state.isFocusOnInput
            }
          />

        <ContactDropdownList
          scrollDirection={this.state.scrollDirection}
          selectedIndex={this.state.selectedContactIndex}
          setSelectedIndex={this.setSelectedIndex}
          addToRecipients={this.props.addToRecipients}
          items={relatedContactList}
          formatContactPhone={this.props.formatContactPhone}
          className={styles.contactsDropdown}
          visibility={this.state.isFocusOnInput}
        />

    );
  }
}

RecipientsInput.propTypes = {
  label: PropTypes.string,
  placeholder: PropTypes.string,
  searchContactList: PropTypes.arrayOf(PropTypes.shape({
    name: PropTypes.string.isRequired,
    entityType: PropTypes.string.isRequired,
    phoneType: PropTypes.string.isRequired,
    phoneNumber: PropTypes.string.isRequired,
  })).isRequired,
  recipients: PropTypes.arrayOf(PropTypes.shape({
    phoneNumber: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
  })).isRequired,
  value: PropTypes.string.isRequired,
  onChange: PropTypes.func.isRequired,
  onClean: PropTypes.func.isRequired,
  onKeyUp: PropTypes.func,
  onKeyDown: PropTypes.func,
  addToRecipients: PropTypes.func.isRequired,
  removeFromRecipients: PropTypes.func.isRequired,
  formatContactPhone: PropTypes.func.isRequired,
};

RecipientsInput.defaultProps = {
  label: null,
  placeholder: '',
  onKeyUp: () => null,
  onKeyDown: () => null,
};

export default RecipientsInput;
<commit_msg>enhance to numbers field in composeText to allow contact with no name to display phoneNumber (#176)<commit_after>import React, { PropTypes, Component } from 'react';
import styles from './styles.scss';
import RemoveButton from '../RemoveButton';
import ContactDropdownList from '../ContactDropdownList';

function SelectedRecipientItem({
  phoneNumber,
  name = phoneNumber,
  onRemove,
}) {
  const className = phoneNumber.length > 5 ? styles.blue : null;
  return (

      {name}
      <RemoveButton
        className={styles.removeReceiver}
        onClick={onRemove}
        visibility
      />

  );
}

SelectedRecipientItem.propTypes = {
  name: PropTypes.string,
  phoneNumber: PropTypes.string.isRequired,
  onRemove: PropTypes.func.isRequired,
};
SelectedRecipientItem.defaultProps = {
  name: undefined,
};

function SelectedRecipients(props) {
  const items = props.items;
  if (items.length < 1) {
    return null;
  }
  return (

      {
        items.map(item => (
          <SelectedRecipientItem
            key={item.phoneNumber}
            name={item.name}
            phoneNumber={item.phoneNumber}
            onRemove={() => props.removeFromRecipients(item.phoneNumber)}
          />
        ))
      }

  );
}

SelectedRecipients.propTypes = {
  removeFromRecipients: PropTypes.func.isRequired,
  items: React.PropTypes.arrayOf(PropTypes.shape({
    phoneNumber: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
  })).isRequired,
};

class RecipientsInput extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isFocusOnInput: false,
      selectedContactIndex: 0,
      scrollDirection: null,
      currentValue: props.value.replace(',', ''),
    };

    this.onReceiversInputFocus = () => {
      this.setState({
        isFocusOnInput: true,
      });
    };

    this.onReceiversInputBlur = () => {
      this.setState({
        isFocusOnInput: false,
      });
    };

    this.setSelectedIndex = (index) => {
      this.setState({
        selectedContactIndex: index,
        scrollDirection: null,
      });
    };
    this.scrollOperation = (direction) => {
      if (direction === 'ArrowDown' || direction === 'ArrowUp') {
        this.setState({
          scrollDirection: direction,
        });
      }
    };
    this.addSelectedContactIndex = () => {
      const length = this.props.searchContactList.length;
      if (this.state.selectedContactIndex >= (length - 1)) {
        this.setState({
          selectedContactIndex: length - 1,
        });
      } else {
        this.setState(preState => ({
          selectedContactIndex: (preState.selectedContactIndex + 1),
        }));
      }
    };

    this.reduceSelectedContactIndex = () => {
      if (this.state.selectedContactIndex > 0) {
        this.setState(preState => ({
          selectedContactIndex: (preState.selectedContactIndex - 1),
        }));
      } else {
        this.setState({
          selectedContactIndex: 0,
        });
      }
    };

    this.handleHotKey = (e) => {
      if (this.state.isFocusOnInput && this.props.value.length >= 3) {
        if (e.key === 'ArrowUp') {
          this.reduceSelectedContactIndex();
          this.scrollOperation(e.key);
        } else if (e.key === 'ArrowDown') {
          this.addSelectedContactIndex();
          this.scrollOperation(e.key);
        }
      } else {
        this.setState({
          selectedContactIndex: 0,
        });
      }
      if (e.key === ',' || e.key === ';' || e.key === 'Enter') {
        e.preventDefault();
        if (this.props.value.length === 0) {
          return;
        }
        const relatedContactList = this.props.value.length >= 3 ?
          this.props.searchContactList : [];
        const currentSelected
          = relatedContactList[this.state.selectedContactIndex];
        if (currentSelected) {
          this.props.addToRecipients({
            name: currentSelected.name,
            phoneNumber: currentSelected.phoneNumber,
          });
        } else {
          this.props.addToRecipients({
            name: this.props.value.replace(',', ''),
            phoneNumber: this.props.value.replace(',', ''),
          });
          this.props.onClean();
        }
        this.props.onClean();
      }
    };
  }
  componentWillReceiveProps(newProps) {
    this.setState({
      currentValue: newProps.value.replace(',', '')
    });
    if (newProps.value &&
        newProps.value !== this.props.value &&
        this.props.value[this.props.value.length - 1] === ',') {
      this.setState({
        isFocusOnInput: true,
      });
      this.props.addToRecipients({
        name: this.props.value.replace(',', ''),
        phoneNumber: this.props.value.replace(',', ''),
      }, false);
    }
  }
  render() {
    const relatedContactList = this.props.value.length >= 3 ?
      this.props.searchContactList : [];
    const label = this.props.label ?
      (
        {this.props.label}
      ) : null;
    return (

        {label}

          <SelectedRecipients
            items={this.props.recipients}
            removeFromRecipients={this.props.removeFromRecipients}
          />

            <input
              name="receiver"
              value={this.state.currentValue}
              onChange={this.props.onChange}
              onKeyUp={this.props.onKeyUp}
              onKeyDown={this.props.onKeyDown}
              className={styles.numberInput}
              maxLength={30}
              onFocus={this.onReceiversInputFocus}
              onBlur={this.onReceiversInputBlur}
              placeholder={this.props.placeholder}
              autoComplete="off"
            />

          <RemoveButton
            className={styles.removeButton}
            onClick={this.props.onClean}
            visibility={
              this.props.value.length > 0 &&
              this.state.isFocusOnInput
            }
          />

        <ContactDropdownList
          scrollDirection={this.state.scrollDirection}
          selectedIndex={this.state.selectedContactIndex}
          setSelectedIndex={this.setSelectedIndex}
          addToRecipients={this.props.addToRecipients}
          items={relatedContactList}
          formatContactPhone={this.props.formatContactPhone}
          className={styles.contactsDropdown}
          visibility={this.state.isFocusOnInput}
        />

    );
  }
}

RecipientsInput.propTypes = {
  label: PropTypes.string,
  placeholder: PropTypes.string,
  searchContactList: PropTypes.arrayOf(PropTypes.shape({
    name: PropTypes.string.isRequired,
    entityType: PropTypes.string.isRequired,
    phoneType: PropTypes.string.isRequired,
    phoneNumber: PropTypes.string.isRequired,
  })).isRequired,
  recipients: PropTypes.arrayOf(PropTypes.shape({
    phoneNumber: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
  })).isRequired,
  value: PropTypes.string.isRequired,
  onChange: PropTypes.func.isRequired,
  onClean: PropTypes.func.isRequired,
  onKeyUp: PropTypes.func,
  onKeyDown: PropTypes.func,
  addToRecipients: PropTypes.func.isRequired,
  removeFromRecipients: PropTypes.func.isRequired,
  formatContactPhone: PropTypes.func.isRequired,
};

RecipientsInput.defaultProps = {
  label: null,
  placeholder: '',
  onKeyUp: () => null,
  onKeyDown: () => null,
};

export default RecipientsInput;
<|endoftext|>


<commit_before>/**
 * Created by Andrea on 01/05/2016.
 */
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import { searchPost, clearSearch } from 'redux/modules/algoliasearch';
import {debounce} from 'throttle-debounce';

@connect(
  state => ({
    results: state.algoliasearch.results,
    error: state.algoliasearch.error,
    searching: state.algoliasearch.searching
  }))
export default class SearchForm extends Component {
  static propTypes = {
    dispatch: PropTypes.func,
    results: PropTypes.array,
    error: PropTypes.string
  }

  constructor() {
    super();
    this.callAlgolia = debounce(500, this.callAlgolia);
  }
  printChange(event) {
    this.callAlgolia(event.target.value);
  }
  callAlgolia(value) {
     if (value.length > 2) {
      this.props.dispatch(searchPost(event.target.value));
    }
    if (value.length === 0) {
      this.props.dispatch(clearSearch());
    }    // call ajax
  }

  render() {
    return (

        <input type="text" onKeyUp={this.printChange.bind(this)} />

    );
  }
}
<commit_msg>first with algolia search<commit_after>/**
 * Created by Andrea on 01/05/2016.
 */
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import { searchPost, clearSearch } from 'redux/modules/algoliasearch';
import {debounce} from 'throttle-debounce';

@connect(
  state => ({
    results: state.algoliasearch.results,
    error: state.algoliasearch.error,
    searching: state.algoliasearch.searching
  }))
export default class SearchForm extends Component {
  static propTypes = {
    dispatch: PropTypes.func,
    results: PropTypes.array,
    error: PropTypes.string
  }

  constructor() {
    super();
    this.callAlgolia = debounce(500, this.callAlgolia);
  }
  printChange(event) {
    this.callAlgolia(event.target.value);
  }
  callAlgolia(value) {
    if (value.length > 2) {
      this.props.dispatch(searchPost(value));
    }
    if (value.length === 0) {
      this.props.dispatch(clearSearch());
    }
  }

  render() {
    return (

        <input type="text" onKeyUp={this.printChange.bind(this)} />

    );
  }
}
<|endoftext|>


<commit_before>import React, {
  Component,
  PropTypes
} from 'react'
import {
  FormGroup,
  FormControl,
  Col,
  Button
} from 'react-bootstrap'
import SearchIcon from 'react-icons/lib/md/search'
import './SearchForm.scss'
export default class SearchForm extends Component {
  static propTypes = {
    isRenderSearchForm2: PropTypes.bool,
    setSearchCategoryValue: PropTypes.func,
    searchCategoryValue: React.PropTypes.string,
    requestSearchNews: React.PropTypes.func,
  // setSearchLanguageValue: React.PropTypes.func
  // searchLanguageValue: React.PropTypes.string,
  // toggleSearchForm: PropTypes.func,
  };

  constructor (props) {
    super(props)
    this.state = { isRenderSearchForm2: false }
  }

  handleToggleClick = () => {
    this.setState({
      isRenderSearchForm2: !this.state.isRenderSearchForm2
    })
  }

  handleSearch = () => {
    const searchParams = {
      category: this.props.searchCategoryValue,
      // language: this.props.searchLanguageValue
    }
    this.props.requestSearchNews(searchParams)
    this.setState({
      isRenderSearchForm2: !this.state.isRenderSearchForm2
    })
  }
  handleCategoryChange = (e) => {
    this.props.setSearchCategoryValue(e.target.value)
  }
  // handleLanguageChange = (e) => {
  //   this.props.setSearchLanguageValue(e.target.value)
  // }

  renderSearchForm (props) {
    if (this.state.isRenderSearchForm2) {
      return (

            <form className='searchFrom'>
              <FormGroup controlId='formHorizontalText'>
                <Col smOffset={4} sm={4}>
                  <FormControl
                    type='text'
                    className='searchInput'
                    placeholder='Category, like: business, entertainment, gaming...'
                    onChange={this.handleCategoryChange}
                  />
                </Col>
              </FormGroup>
              {/* <Row>

OR

               </Row> */}
              {/* <FormGroup controlId='formHorizontalPassword'>
                <Col cozmponentClass={ControlLabel} smOffset={4} sm={1}>
                 language
                 </Col>
                <Col smOffset={4} sm={4}>
                  <FormControl
                    className='searchInput'
                    type='text'
                    placeholder='en, de, fr ...'
                    onChange={this.handleLanguageChange} />
                </Col>
              </FormGroup> */}

              <FormGroup>
                <Col smOffset={4} sm={4} className='buttonWraper'>
                  <Button
                    className='searchButton'
                    onClick={this.handleSearch}>
                    Search
                  </Button>
                </Col>
              </FormGroup>
            </form>

      )
    }
  }

  render () {
    return (

          <SearchIcon size={30} />

        {this.renderSearchForm()}

    )
  }
}
<commit_msg>delete commands<commit_after>import React, {
  Component,
  PropTypes
} from 'react'
import {
  FormGroup,
  FormControl,
  Col,
  Button
} from 'react-bootstrap'
import SearchIcon from 'react-icons/lib/md/search'
import './SearchForm.scss'
export default class SearchForm extends Component {
  static propTypes = {
    isRenderSearchForm2: PropTypes.bool,
    setSearchCategoryValue: PropTypes.func,
    searchCategoryValue: React.PropTypes.string,
    requestSearchNews: React.PropTypes.func
    // setSearchLanguageValue: React.PropTypes.func
    // searchLanguageValue: React.PropTypes.string,
    // toggleSearchForm: PropTypes.func,
  };

  constructor (props) {
    super(props)
    this.state = { isRenderSearchForm2: false }
  }

  handleToggleClick = () => {
    this.setState({
      isRenderSearchForm2: !this.state.isRenderSearchForm2
    })
  }

  handleSearch = () => {
    const searchParams = {
      category: this.props.searchCategoryValue
    }
    this.props.requestSearchNews(searchParams)
    this.setState({
      isRenderSearchForm2: !this.state.isRenderSearchForm2
    })
  }
  handleCategoryChange = (e) => {
    this.props.setSearchCategoryValue(e.target.value)
  }

  renderSearchForm (props) {
    if (this.state.isRenderSearchForm2) {
      return (

            <form className='searchFrom'>
              <FormGroup controlId='formHorizontalText'>
                <Col smOffset={4} sm={4}>
                  <FormControl
                    type='text'
                    className='searchInput'
                    placeholder='Category, like: business, entertainment, gaming...'
                    onChange={this.handleCategoryChange}
                  />
                </Col>
              </FormGroup>
              <FormGroup>
                <Col smOffset={4} sm={4} className='buttonWraper'>
                  <Button
                    className='searchButton'
                    onClick={this.handleSearch}>
                    Search
                  </Button>
                </Col>
              </FormGroup>
            </form>

      )
    }
  }

  render () {
    return (

          <SearchIcon size={30} />

        {this.renderSearchForm()}

    )
  }
}
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react'

import {
  MAIN_BRICK,
  TEST_INPUT
} from '../utils/componentNames'

import {
  PositionPropTypes,
  PrimitivePropTypes
} from '../propTypes'

const baseStyles = {
  backgroundColor: 'rgba(0, 0, 255, 0.5)',
  padding: 6,
  position: 'absolute'
}

const translations = {
  en: {
    addUnitTest: 'Add unit test',
    delete: 'Delete',
    empty: 'None',
    type: 'Type: ',
    value: 'Value: '
  }
}

export default class SelectedElementDialog extends Component {
  constructor(props) {
    super(props)

    this.renderElementDetails = this.renderElementDetails.bind(this)
  }

  renderElementDetails() {
    const {
      componentName,
      id
    } = this.props

    switch (componentName) {
      case MAIN_BRICK:
        const {
          addUnitTest
        } = this.props

        return (
          <button
            onClick={ addUnitTest }
          >
            { translations['en'].addUnitTest }
          </button>
        )
      case TEST_INPUT:
        const {
          changePrimitiveType,
          changePrimitiveValue,
          primitives,
          type,
          value
        } = this.props

        return (

                { translations['en'].type }

              <select
                value={ type }
                onChange={ (e) => changePrimitiveType(id, e) }
              >
                { /* TestInput 'type' will be 'null' by default */ }
                <option
                  disabled
                  value="null"
                >
                  { translations['en'].empty }
                </option>

                { primitives.map((primitive) =>
                    <option
                      key={ primitive.id }
                      value={ primitive.type }
                    >
                      { primitive.label }
                    </option>
                ) }
              </select>

                { translations['en'].value }

              <input
                value={ value }
                onChange={ (e) => changePrimitiveValue(id, e) }
              />

        )
      default:
        const {
          deleteElement
        } = this.props

        return (
          <button
            onClick={ () => deleteElement(id) }
          >
            { translations['en'].delete }
          </button>
        )
    }
  }

  render() {
    const {
      mousePosition
    } = this.props

    const styles = Object.assign({}, baseStyles, {
      left: mousePosition.x,
      top: mousePosition.y
    })

    return (

        { this.renderElementDetails() }

    )
  }
}

SelectedElementDialog.propTypes = {
  addUnitTest: PropTypes.func.isRequired,
  changePrimitiveType: PropTypes.func.isRequired,
  changePrimitiveValue: PropTypes.func.isRequired,
  componentName: PropTypes.string.isRequired,
  deleteElement: PropTypes.func.isRequired,
  id: PropTypes.number.isRequired,
  mousePosition: PositionPropTypes.isRequired,
  primitives: PropTypes.arrayOf(PrimitivePropTypes).isRequired
}
<commit_msg>Change 'value' prop of Primitive<commit_after>import React, { PropTypes, Component } from 'react'

import {
  MAIN_BRICK,
  PRIMITIVE,
  TEST_INPUT
} from '../utils/componentNames'

import {
  PositionPropTypes,
  PrimitivePropTypes
} from '../propTypes'

const baseStyles = {
  backgroundColor: 'rgba(0, 0, 255, 0.5)',
  padding: 6,
  position: 'absolute'
}

const translations = {
  en: {
    addUnitTest: 'Add unit test',
    delete: 'Delete',
    empty: 'None',
    type: 'Type: ',
    value: 'Value: '
  }
}

export default class SelectedElementDialog extends Component {
  constructor(props) {
    super(props)

    this.renderDeleteElementButton = this.renderDeleteElementButton.bind(this)
    this.renderElementDetails = this.renderElementDetails.bind(this)
    this.renderPrimitiveValueInput = this.renderPrimitiveValueInput.bind(this)
  }

  renderElementDetails() {
    const {
      componentName,
      id
    } = this.props

    switch (componentName) {
      case MAIN_BRICK:
        const {
          addUnitTest
        } = this.props

        return (
          <button
            onClick={ addUnitTest }
          >
            { translations['en'].addUnitTest }
          </button>
        )
      case PRIMITIVE:
        return (

            { this.renderPrimitiveValueInput() }
            { this.renderDeleteElementButton() }

        )
      case TEST_INPUT:
        const {
          changePrimitiveType,
          primitives,
          type
        } = this.props

        return (

                { translations['en'].type }

              <select
                value={ type }
                onChange={ (e) => changePrimitiveType(id, e) }
              >
                { /* TestInput 'type' will be 'null' by default */ }
                <option
                  disabled
                  value="null"
                >
                  { translations['en'].empty }
                </option>

                { primitives.map((primitive) =>
                    <option
                      key={ primitive.id }
                      value={ primitive.type }
                    >
                      { primitive.label }
                    </option>
                ) }
              </select>

            { this.renderPrimitiveValueInput() }

        )
      default:
        return this.renderDeleteElementButton()
    }
  }

  renderDeleteElementButton() {
    const {
      deleteElement,
      id
    } = this.props

    return (
      <button
        onClick={ () => deleteElement(id) }
      >
        { translations['en'].delete }
      </button>
    )
  }

  renderPrimitiveValueInput() {
    const {
      changePrimitiveValue,
      id,
      value
    } = this.props

    return (

          { translations['en'].value }

        <input
          value={ value }
          onChange={ (e) => changePrimitiveValue(id, e) }
        />

    )
  }

  render() {
    const {
      mousePosition
    } = this.props

    const styles = Object.assign({}, baseStyles, {
      left: mousePosition.x,
      top: mousePosition.y
    })

    return (

        { this.renderElementDetails() }

    )
  }
}

SelectedElementDialog.propTypes = {
  addUnitTest: PropTypes.func.isRequired,
  changePrimitiveType: PropTypes.func.isRequired,
  changePrimitiveValue: PropTypes.func.isRequired,
  componentName: PropTypes.string.isRequired,
  deleteElement: PropTypes.func.isRequired,
  id: PropTypes.number.isRequired,
  mousePosition: PositionPropTypes.isRequired,
  primitives: PropTypes.arrayOf(PrimitivePropTypes).isRequired
}
<|endoftext|>


<commit_before>import * as component from './component';
import { COMPONENT_TYPE } from 'constants/pogues-constants';

const { QUESTION, SUBSEQUENCE, SEQUENCE } = COMPONENT_TYPE;

jest.mock('./component-move');
jest.mock('./component-update');
jest.mock('./component-remove');
jest.mock('./component-insert');

describe('updateParentChildren', () => {
  function getState() {
    return {
      appState: {
        activeComponentsById: { '99': {}, '2': { id: '2', parent: '99', children: [] } },
      },
    };
  }
  const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2' } } } };
  const fn = component.updateParentChildren(payload);

  test(`should trigger the UPDATE_COMPONENT action`, () => {
    function dispatch(param) {
      expect(param.type).toEqual(component.UPDATE_COMPONENT);
    }
    fn(dispatch, getState);
  });

  test(`should return the ID of the new component`, () => {
    function dispatch(param) {
      expect(param.payload.id).toEqual(payload.payload.id);
    }
    fn(dispatch, getState);
  });

  test(`should call return the last created component`, () => {
    function dispatch(param) {
      expect(param.payload.lastCreatedComponent).toEqual(payload.payload.lastCreatedComponent);
    }
    fn(dispatch, getState);
  });

  test(`should call return the updated parent`, () => {
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ '2': { id: '2', children: ['1'], parent: '99' } });
    }
    fn(dispatch, getState);
  });
});

describe('orderComponents', () => {
  test(`should trigger the UPDATE_COMPONENT action`, () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '99': { children: [] }, '2': { parent: '99', id: '2', children: [] } },
          selectedComponentId: '2',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2' } } } };
    const fn = component.orderComponents(payload);

    function dispatch(param) {
      expect(param.type).toEqual(component.UPDATE_COMPONENT);
    }
    fn(dispatch, getState);
  });

  test(`should return the ID of the new component`, () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '99': { children: [] }, '2': { parent: '99', id: '2', children: [] } },
          selectedComponentId: '2',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2' } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.id).toEqual(payload.payload.id);
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a question next to a question, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '99': { children: [] },
            '2': { parent: '99', id: '2', children: [], type: QUESTION },
          },
          selectedComponentId: '2',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: QUESTION } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a question next to a subsequence, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '99': { children: [] },
            '2': { parent: '99', id: '2', children: [], type: SUBSEQUENCE },
          },
          selectedComponentId: '2',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: QUESTION } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a question next to a sequence, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '99': { children: [] },
            '2': { parent: '99', id: '2', children: [], type: SEQUENCE },
          },
          selectedComponentId: '2',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: QUESTION } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a sequence next to a question, should call moveQuestionAndSubSequenceToSequence', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] }, '3': { parent: '2', type: QUESTION, children: [] } },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SEQUENCE } } } };
    const fn = component.orderComponents(payload);

    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ moveQuestionAndSubSequenceToSequence: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a sequence next to a subsequence, should call moveQuestionAndSubSequenceToSequence', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: [] },
            '3': { parent: '2', type: SUBSEQUENCE, children: [] },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SEQUENCE } } } };
    const fn = component.orderComponents(payload);

    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ moveQuestionAndSubSequenceToSequence: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a sequence next to a sequence with children, should call moveQuestionAndSubSequenceToSequence', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: [] },
            '3': { id: '3', parent: '2', type: SEQUENCE, children: ['5'] },
            '5': { id: '5', type: QUESTION, children: [], weight: 0 },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SEQUENCE } } } };
    const fn = component.orderComponents(payload);

    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ moveQuestionAndSubSequenceToSequence: true });
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a sequence next to a sequence without children, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: [] },
            '3': { parent: '2', type: SEQUENCE, children: [] },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SEQUENCE } } } };
    const fn = component.orderComponents(payload);

    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a subsequence next to a QUESTION with a question as sibling, should call moveQuestionToSubSequence', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: ['3', '4'] },
            '3': { parent: '2', type: QUESTION, children: [], weight: 0 },
            '4': { parent: '2', type: QUESTION, children: [], weight: 1 },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SUBSEQUENCE } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ moveQuestionToSubSequence: true });
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a subsequence next to a QUESTION without a QUESTION as sibling, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] }, '3': { parent: '2', type: QUESTION, children: [] } },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SUBSEQUENCE } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a subsequence next to a subsequence with children, should call moveQuestionToSubSequence', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: [], type: SEQUENCE },
            '3': { id: '3', type: SUBSEQUENCE, parent: '2', children: ['4', '5'] },
            '4': { id: '4', parent: '3', children: [], type: QUESTION, weight: 0 },
            '5': { id: '5', parent: '3', children: [], type: QUESTION, weight: 1 },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = {
      payload: { id: '1', lastCreatedComponent: { '1': { id: '1', parent: '2', type: SUBSEQUENCE } } },
    };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ moveQuestionToSubSequence: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a subsequence next to a SUBSEQUENCE without children, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: [] },
            '3': { parent: '2', type: SUBSEQUENCE, children: [] },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SUBSEQUENCE } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a subsequence next to a sequence, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] }, '3': { parent: '2', type: SEQUENCE, children: [] } },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SUBSEQUENCE } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });
});

describe('dragComponent', () => {
  test('should trigger the MOVE_COMPONENT action', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.dragComponent('1', '2', 1);

    function dispatch(param) {
      expect(param.type).toEqual(component.MOVE_COMPONENT);
    }
    fn(dispatch, getState);
  });

  test('should call moveComponent with the right parameter', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.dragComponent('1', '2', 1);

    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({
        activesComponents: { '2': { id: '2', children: [] } },
        idMovedComponent: '1',
        idTargetComponent: '2',
        newWeight: 1,
      });
    }
    fn(dispatch, getState);
  });
});

describe('removeComponent', () => {
  test('should trigger the REMOVE_COMPONENT action', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.removeComponent('1');

    function dispatch(param) {
      expect(param.type).toEqual(component.REMOVE_COMPONENT);
    }
    fn(dispatch, getState);
  });

  test('should call remove with the right parameter', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.removeComponent('1');

    function dispatch(param) {
      expect(param.payload).toEqual({
        activeComponentsById: getState().appState.activeComponentsById,
        idDeletedComponent: '1',
      });
    }
    fn(dispatch, getState);
  });
});

describe('duplicateComponent', () => {
  test('should trigger the CREATE_COMPONENT action', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.duplicateComponent('1');

    function dispatch(param) {
      expect(param.type).toEqual(component.CREATE_COMPONENT);
    }
    fn(dispatch, getState);
  });

  test('should call duplicate function with the right parameters', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.duplicateComponent('2');

    function dispatch(param) {
      expect(param.payload).toEqual({
        update: {
          activeComponentsById: {
            activesComponents: getState().appState.activeComponentsById,
            idComponent: '2',
          },
        },
      });
    }
    fn(dispatch, getState);
  });
});
<commit_msg>[TESTS] Fixing tests<commit_after>import * as component from './component';
import { COMPONENT_TYPE } from 'constants/pogues-constants';

const { QUESTION, SUBSEQUENCE, SEQUENCE } = COMPONENT_TYPE;

jest.mock('./component-move');
jest.mock('./component-update');
jest.mock('./component-remove');
jest.mock('./component-insert');

describe('updateParentChildren', () => {
  function getState() {
    return {
      appState: {
        activeComponentsById: { '99': {}, '2': { id: '2', parent: '99', children: [] } },
      },
    };
  }
  const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2' } } } };
  const fn = component.updateParentChildren(payload);

  test(`should trigger the UPDATE_COMPONENT_PARENT action`, () => {
    function dispatch(param) {
      expect(param.type).toEqual(component.UPDATE_COMPONENT_PARENT);
    }
    fn(dispatch, getState);
  });

  test(`should return the ID of the new component`, () => {
    function dispatch(param) {
      expect(param.payload.id).toEqual(payload.payload.id);
    }
    fn(dispatch, getState);
  });

  test(`should call return the last created component`, () => {
    function dispatch(param) {
      expect(param.payload.lastCreatedComponent).toEqual(payload.payload.lastCreatedComponent);
    }
    fn(dispatch, getState);
  });

  test(`should call return the updated parent`, () => {
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ '2': { id: '2', children: ['1'], parent: '99' } });
    }
    fn(dispatch, getState);
  });
});

describe('orderComponents', () => {
  test(`should trigger the UPDATE_COMPONENT_ORDER action`, () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '99': { children: [] }, '2': { parent: '99', id: '2', children: [] } },
          selectedComponentId: '2',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2' } } } };
    const fn = component.orderComponents(payload);

    function dispatch(param) {
      expect(param.type).toEqual(component.UPDATE_COMPONENT_ORDER);
    }
    fn(dispatch, getState);
  });

  test(`should return the ID of the new component`, () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '99': { children: [] }, '2': { parent: '99', id: '2', children: [] } },
          selectedComponentId: '2',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2' } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.id).toEqual(payload.payload.id);
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a question next to a question, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '99': { children: [] },
            '2': { parent: '99', id: '2', children: [], type: QUESTION },
          },
          selectedComponentId: '2',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: QUESTION } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a question next to a subsequence, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '99': { children: [] },
            '2': { parent: '99', id: '2', children: [], type: SUBSEQUENCE },
          },
          selectedComponentId: '2',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: QUESTION } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a question next to a sequence, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '99': { children: [] },
            '2': { parent: '99', id: '2', children: [], type: SEQUENCE },
          },
          selectedComponentId: '2',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: QUESTION } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a sequence next to a question, should call moveQuestionAndSubSequenceToSequence', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] }, '3': { parent: '2', type: QUESTION, children: [] } },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SEQUENCE } } } };
    const fn = component.orderComponents(payload);

    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ moveQuestionAndSubSequenceToSequence: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a sequence next to a subsequence, should call moveQuestionAndSubSequenceToSequence', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: [] },
            '3': { parent: '2', type: SUBSEQUENCE, children: [] },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SEQUENCE } } } };
    const fn = component.orderComponents(payload);

    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ moveQuestionAndSubSequenceToSequence: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a sequence next to a sequence with children, should call moveQuestionAndSubSequenceToSequence', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: [] },
            '3': { id: '3', parent: '2', type: SEQUENCE, children: ['5'] },
            '5': { id: '5', type: QUESTION, children: [], weight: 0 },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SEQUENCE } } } };
    const fn = component.orderComponents(payload);

    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ moveQuestionAndSubSequenceToSequence: true });
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a sequence next to a sequence without children, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: [] },
            '3': { parent: '2', type: SEQUENCE, children: [] },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SEQUENCE } } } };
    const fn = component.orderComponents(payload);

    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a subsequence next to a QUESTION with a question as sibling, should call moveQuestionToSubSequence', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: ['3', '4'] },
            '3': { parent: '2', type: QUESTION, children: [], weight: 0 },
            '4': { parent: '2', type: QUESTION, children: [], weight: 1 },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SUBSEQUENCE } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ moveQuestionToSubSequence: true });
    }
    fn(dispatch, getState);
  });

  test('when we want to insert a subsequence next to a QUESTION without a QUESTION as sibling, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] }, '3': { parent: '2', type: QUESTION, children: [] } },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SUBSEQUENCE } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a subsequence next to a subsequence with children, should call moveQuestionToSubSequence', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: [], type: SEQUENCE },
            '3': { id: '3', type: SUBSEQUENCE, parent: '2', children: ['4', '5'] },
            '4': { id: '4', parent: '3', children: [], type: QUESTION, weight: 0 },
            '5': { id: '5', parent: '3', children: [], type: QUESTION, weight: 1 },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = {
      payload: { id: '1', lastCreatedComponent: { '1': { id: '1', parent: '2', type: SUBSEQUENCE } } },
    };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ moveQuestionToSubSequence: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a subsequence next to a SUBSEQUENCE without children, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: {
            '2': { id: '2', children: [] },
            '3': { parent: '2', type: SUBSEQUENCE, children: [] },
          },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SUBSEQUENCE } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });
  test('when we want to insert a subsequence next to a sequence, should call increaseWeightOfAll', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] }, '3': { parent: '2', type: SEQUENCE, children: [] } },
          selectedComponentId: '3',
        },
      };
    }
    const payload = { payload: { id: '1', lastCreatedComponent: { '1': { parent: '2', type: SUBSEQUENCE } } } };
    const fn = component.orderComponents(payload);
    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({ increaseWeightOfAll: true });
    }
    fn(dispatch, getState);
  });
});

describe('dragComponent', () => {
  test('should trigger the MOVE_COMPONENT action', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.dragComponent('1', '2', 1);

    function dispatch(param) {
      expect(param.type).toEqual(component.MOVE_COMPONENT);
    }
    fn(dispatch, getState);
  });

  test('should call moveComponent with the right parameter', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.dragComponent('1', '2', 1);

    function dispatch(param) {
      expect(param.payload.update.activeComponentsById).toEqual({
        activesComponents: { '2': { id: '2', children: [] } },
        idMovedComponent: '1',
        idTargetComponent: '2',
        newWeight: 1,
      });
    }
    fn(dispatch, getState);
  });
});

describe('removeComponent', () => {
  test('should trigger the REMOVE_COMPONENT action', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.removeComponent('1');

    function dispatch(param) {
      expect(param.type).toEqual(component.REMOVE_COMPONENT);
    }
    fn(dispatch, getState);
  });

  test('should call remove with the right parameter', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.removeComponent('1');

    function dispatch(param) {
      expect(param.payload).toEqual({
        activeComponentsById: getState().appState.activeComponentsById,
        idDeletedComponent: '1',
      });
    }
    fn(dispatch, getState);
  });
});

describe('duplicateComponent', () => {
  test('should trigger the CREATE_COMPONENT action', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.duplicateComponent('1');

    function dispatch(param) {
      expect(param.type).toEqual(component.CREATE_COMPONENT);
    }
    fn(dispatch, getState);
  });

  test('should call duplicate function with the right parameters', () => {
    function getState() {
      return {
        appState: {
          activeComponentsById: { '2': { id: '2', children: [] } },
        },
      };
    }
    const fn = component.duplicateComponent('2');

    function dispatch(param) {
      expect(param.payload).toEqual({
        update: {
          activeComponentsById: {
            activesComponents: getState().appState.activeComponentsById,
            idComponent: '2',
          },
        },
      });
    }
    fn(dispatch, getState);
  });
});
<|endoftext|>


<commit_before>import React from 'react'
import {statusMessageFromRole} from 'extensions/statusUtils'
import classes from './StatusText.scss'

class StatusText extends React.Component {

  static propTypes = {
    status: React.PropTypes.string.isRequired,
    email: React.PropTypes.string.isRequired
  }

  render () {
    return (

          {generateMessage(this.props.status, this.props.email)}

    )
  }
}

function generateMessage (status, email) {
  if (status === 'accepted') {
    return generateAcceptedJSX(email)
  } else if (status === 'confirmed') {
    return generateConfirmedJSX(email)
  } else {
    return statusMessageFromRole(status)
  }
}

function generateConfirmedJSX (email) {
  return (

      {'Whoo! We can\'t wait to see you! If you\'re flying or driving from out-of-state, we will reimburse up to $200 for flights and $50 for gas, but we can\'t reimburse people from schools with buses.'}

  )
}

function generateAcceptedJSX (email) {
  return (

      {'Congratulations! You’ve been accepted! Please'}
      {' '}
      {'confirm'}
      {' '}
      {'you\'re coming by '}

        Thursday, 11/17.

      {' Our process has been more rigorous than in previous years, so you must confirm to guarantee your spot. We won\'t be accepting walk-ins the day of.'}

  )
}

export default StatusText
<commit_msg>updated confirm date<commit_after>import React from 'react'
import {statusMessageFromRole} from 'extensions/statusUtils'
import classes from './StatusText.scss'

class StatusText extends React.Component {

  static propTypes = {
    status: React.PropTypes.string.isRequired,
    email: React.PropTypes.string.isRequired
  }

  render () {
    return (

          {generateMessage(this.props.status, this.props.email)}

    )
  }
}

function generateMessage (status, email) {
  if (status === 'accepted') {
    return generateAcceptedJSX(email)
  } else if (status === 'confirmed') {
    return generateConfirmedJSX(email)
  } else {
    return statusMessageFromRole(status)
  }
}

function generateConfirmedJSX (email) {
  return (

      {'Whoo! We can\'t wait to see you! If you\'re flying or driving from out-of-state, we will reimburse up to $200 for flights and $50 for gas, but we can\'t reimburse people from schools with buses.'}

  )
}

function generateAcceptedJSX (email) {
  return (

      {'Congratulations! You’ve been accepted! Please'}
      {' '}
      {'confirm'}
      {' '}
      {'you\'re coming by '}

        Wed, 10/18.

      {' Our process has been more rigorous than in previous years, so you must confirm to guarantee your spot. We won\'t be accepting walk-ins the day of.'}

  )
}

export default StatusText
<|endoftext|>


<commit_before>'use strict';

const getChannelURL = require('ember-source-channel-url');
const { embroiderSafe, embroiderOptimized } = require('@embroider/test-setup');

module.exports = async function () {
  return {
    useYarn: true,
    scenarios: [
      {
        name: 'ember-lts-3.8',
        npm: {
          devDependencies: {
            'ember-source': '~3.8.0',
            'ember-angle-bracket-invocation-polyfill': '^3.0.0',
            'ember-decorators-polyfill': '^1.1.5',
            'ember-on-modifier': '^1.0.1',
          },
        },
      },
      {
        name: 'ember-lts-3.12',
        npm: {
          devDependencies: {
            'ember-source': '~3.12.0',
          },
        },
      },
      {
        name: 'ember-lts-3.16',
        npm: {
          devDependencies: {
            'ember-source': '~3.16.0',
          },
        },
      },
      {
        name: 'ember-lts-3.20',
        npm: {
          devDependencies: {
            'ember-source': '~3.20.5',
          },
        },
      },
      {
        name: 'ember-lts-3.24',
        npm: {
          devDependencies: {
            'ember-source': '~3.24.3',
          },
        },
      },
      {
        name: 'ember-release',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('release'),
          },
        },
      },
      {
        name: 'ember-beta',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('beta'),
          },
        },
      },
      {
        name: 'ember-canary',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('canary'),
          },
        },
      },
      {
        name: 'ember-default',
        npm: {
          devDependencies: {},
        },
      },
      {
        name: 'typescript-3.7',
        npm: {
          devDependencies: {
            typescript: '~3.7.0',
          },
        },
        command: 'tsc',
      },
      {
        name: 'typescript-3.9',
        npm: {
          devDependencies: {
            typescript: '~3.9.0',
          },
        },
        command: 'tsc',
      },
      embroiderSafe(),
      embroiderOptimized(),
    ],
  };
};
<commit_msg>Use ember-auto-import 2 in beta & canary scenarios<commit_after>'use strict';

const getChannelURL = require('ember-source-channel-url');
const { embroiderSafe, embroiderOptimized } = require('@embroider/test-setup');

module.exports = async function () {
  return {
    useYarn: true,
    scenarios: [
      {
        name: 'ember-lts-3.8',
        npm: {
          devDependencies: {
            'ember-source': '~3.8.0',
            'ember-angle-bracket-invocation-polyfill': '^3.0.0',
            'ember-decorators-polyfill': '^1.1.5',
            'ember-on-modifier': '^1.0.1',
          },
        },
      },
      {
        name: 'ember-lts-3.12',
        npm: {
          devDependencies: {
            'ember-source': '~3.12.0',
          },
        },
      },
      {
        name: 'ember-lts-3.16',
        npm: {
          devDependencies: {
            'ember-source': '~3.16.0',
          },
        },
      },
      {
        name: 'ember-lts-3.20',
        npm: {
          devDependencies: {
            'ember-source': '~3.20.5',
          },
        },
      },
      {
        name: 'ember-lts-3.24',
        npm: {
          devDependencies: {
            'ember-source': '~3.24.3',
          },
        },
      },
      {
        name: 'ember-release',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('release'),
          },
        },
      },
      {
        name: 'ember-beta',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('beta'),
            'ember-auto-import': '^2.0.0',
            webpack: '^5.0.0',
          },
        },
      },
      {
        name: 'ember-canary',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('canary'),
            'ember-auto-import': '^2.0.0',
            webpack: '^5.0.0',
          },
        },
      },
      {
        name: 'ember-default',
        npm: {
          devDependencies: {},
        },
      },
      {
        name: 'typescript-3.7',
        npm: {
          devDependencies: {
            typescript: '~3.7.0',
          },
        },
        command: 'tsc',
      },
      {
        name: 'typescript-3.9',
        npm: {
          devDependencies: {
            typescript: '~3.9.0',
          },
        },
        command: 'tsc',
      },
      embroiderSafe(),
      embroiderOptimized(),
    ],
  };
};
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 *
 * Copyright (c) 2009 Aptana, Inc.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * ***** END LICENSE BLOCK ***** */

var Indicies = {
    initializeIndicies: function initializeIndicies(storage)
    {
        var model_name, model, table_name, index_name, index, index_callbacks, id;
        for(model_name in ActiveRecord.Models)
        {
            model = ActiveRecord.Models[model_name];
            if(model.indexingCallbacks)
            {
                table_name = model.tableName;
                for(index_name in model.indexingCallbacks)
                {
                    index = model.indexed[index_name];
                    index_callbacks = model.indexingCallbacks[index_name];
                    for(id in storage[table_name])
                    {
                        index_callbacks.afterSave(index,storage[table_name][id]);
                    }
                }
            }
        }

    }
};

/**
 * Warning: this functionality is only available when using the InMemory adapter.
 *
 * Allows the construction of arbitrary data indicies from data in your models.
 * Indicies will stay up to date as records are created, saved or destroyed.
 *
 * The afterSave and afterDestroy objects will only receive the data for a
 * given record (generated with instance.toObject()). The afterSave callback
 * will handle both the create and update scenarios.
 *
 *     Photo.addIndex('byName',{},{
 *         afterSave: function(index,photo){
 *             index[photo.name] = photo.id;
 *         },
 *         afterDestroy: function(index,photo){
 *             delete index[photo.name];
 *         }
 *     });
 *     var flower_record = Photo.create({name:'flower'});
 *     Photo.indexed.byName.flower == flower_record;
 *
 * If you only need to index by a particular key as in the example above
 * you can abbreviate the code above:
 *
 *     Photo.addIndex('byName','name'):
 *
 * A more complicated example, which pre fills an index object:
 *
 *     var index = {a:{},b:{},c:{}};
 *
 *     Contact.addIndex('byLetter',index,{
 *         afterSave: function(index,contact){
 *             var first_letter = contact.name.substring(0,1).toLowerCase();
 *             index[first_letter][contact.id] = contact;
 *         },
 *         afterDestroy: function(index,contact){
 *             var first_letter = contact.name.substring(0,1).toLowerCase();
 *             delete index[first_letter][contact.id];
 *         }
 *     });
 *
 *     //the index will now be available at:
 *     Contact.indexed.byLetter;
 *
 *     Contact.create({name: 'Abbey'});
 *
 *     for(var id in Contact.indexed.byLetter.a){}
 *
 * @alias ActiveRecord.Class.addIndex
 * @param {String} index_name
 * @param {Object} index
 * @param {Object} callbacks
 *     Must contain "afterSave" and "afterDestroy" keys containing callback functions.
 */
ActiveRecord.ClassMethods.addIndex = function addIndex(name,index,callbacks)
{
    if(!callbacks)
    {
        if(typeof(index) == 'string')
        {
            var key_name = index;
            index = {};
            callbacks = {
                afterSave: function afterSaveIndexCallback(index,item){
                    index[item[key_name]] = item.id;
                },
                afterDestroy: function afterDestroyIndexCallback(index,item){
                    delete index[item[key_name]];
                }
            };
        }
        else
        {
            callbacks = index;
            index = {};
        }
    }
    if(!this.indexed)
    {
        this.indexed = {};
    }
    if(!this.indexingCallbacks)
    {
        this.indexingCallbacks = {};
    }
    if(!this.indexingCallbackObservers)
    {
        this.indexingCallbackObservers = {};
    }
    this.indexed[name] = index || {};
    this.indexingCallbacks[name] = callbacks;
    this.indexingCallbackObservers[name] = {};
    this.indexingCallbackObservers[name].afterSave = this.observe('afterSave',ActiveSupport.bind(function afterSaveIndexObserver(instance){
        callbacks.afterSave(this.indexed[name],instance.toObject());
    },this));
    this.indexingCallbackObservers[name].afterDestroy = this.observe('afterDestroy',ActiveSupport.bind(function afterDestroyIndexObserver(instance){
        callbacks.afterDestroy(this.indexed[name],instance.toObject());
    },this));
};

/**
 * @alias ActiveRecord.Class.removeIndex
 * @param {String} index_name
 */
ActiveRecord.ClassMethods.removeIndex = function removeIndex(name)
{
    this.stopObserving('afterSave',this.indexingCallbackObservers[name].afterSave);
    this.stopObserving('afterDestroy',this.indexingCallbackObservers[name].afterDestroy);
    delete this.indexingCallbacks[name];
    delete this.indexed[name];
};

ActiveRecord.Indicies = Indicies;<commit_msg>documentation addition<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 *
 * Copyright (c) 2009 Aptana, Inc.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * ***** END LICENSE BLOCK ***** */

var Indicies = {
    initializeIndicies: function initializeIndicies(storage)
    {
        var model_name, model, table_name, index_name, index, index_callbacks, id;
        for(model_name in ActiveRecord.Models)
        {
            model = ActiveRecord.Models[model_name];
            if(model.indexingCallbacks)
            {
                table_name = model.tableName;
                for(index_name in model.indexingCallbacks)
                {
                    index = model.indexed[index_name];
                    index_callbacks = model.indexingCallbacks[index_name];
                    for(id in storage[table_name])
                    {
                        index_callbacks.afterSave(index,storage[table_name][id]);
                    }
                }
            }
        }

    }
};

/**
 * Warning: this functionality is only available when using the InMemory adapter.
 *
 * Allows the construction of arbitrary data indicies from data in your models.
 * Indicies will stay up to date as records are created, saved or destroyed.
 *
 * The afterSave and afterDestroy objects will only receive the data for a
 * given record (generated with instance.toObject()). The afterSave callback
 * will handle both the create and update scenarios.
 *
 *     Photo.addIndex('byName',{},{
 *         afterSave: function(index,photo){
 *             index[photo.name] = photo.id;
 *         },
 *         afterDestroy: function(index,photo){
 *             delete index[photo.name];
 *         }
 *     });
 *     var flower_record = Photo.create({name:'flower'});
 *     Photo.indexed.byName.flower == flower_record;
 *
 * If you only need and index of key => id pairs (name => id pairs in the
 * example above), you can shorten the call to the following:
 *
 *     Photo.addIndex('byName','name'):
 *
 * A more complicated example, which pre fills an index object:
 *
 *     var index = {a:{},b:{},c:{}};
 *
 *     Contact.addIndex('byLetter',index,{
 *         afterSave: function(index,contact){
 *             var first_letter = contact.name.substring(0,1).toLowerCase();
 *             index[first_letter][contact.id] = contact;
 *         },
 *         afterDestroy: function(index,contact){
 *             var first_letter = contact.name.substring(0,1).toLowerCase();
 *             delete index[first_letter][contact.id];
 *         }
 *     });
 *
 *     //the index will now be available at:
 *     Contact.indexed.byLetter;
 *
 *     Contact.create({name: 'Abbey'});
 *
 *     for(var id in Contact.indexed.byLetter.a){}
 *
 * @alias ActiveRecord.Class.addIndex
 * @param {String} index_name
 * @param {Object} index
 * @param {Object} callbacks
 *     Must contain "afterSave" and "afterDestroy" keys containing callback functions.
 */
ActiveRecord.ClassMethods.addIndex = function addIndex(name,index,callbacks)
{
    if(!callbacks)
    {
        if(typeof(index) == 'string')
        {
            var key_name = index;
            index = {};
            callbacks = {
                afterSave: function afterSaveIndexCallback(index,item){
                    index[item[key_name]] = item.id;
                },
                afterDestroy: function afterDestroyIndexCallback(index,item){
                    delete index[item[key_name]];
                }
            };
        }
        else
        {
            callbacks = index;
            index = {};
        }
    }
    if(!this.indexed)
    {
        this.indexed = {};
    }
    if(!this.indexingCallbacks)
    {
        this.indexingCallbacks = {};
    }
    if(!this.indexingCallbackObservers)
    {
        this.indexingCallbackObservers = {};
    }
    this.indexed[name] = index || {};
    this.indexingCallbacks[name] = callbacks;
    this.indexingCallbackObservers[name] = {};
    this.indexingCallbackObservers[name].afterSave = this.observe('afterSave',ActiveSupport.bind(function afterSaveIndexObserver(instance){
        callbacks.afterSave(this.indexed[name],instance.toObject());
    },this));
    this.indexingCallbackObservers[name].afterDestroy = this.observe('afterDestroy',ActiveSupport.bind(function afterDestroyIndexObserver(instance){
        callbacks.afterDestroy(this.indexed[name],instance.toObject());
    },this));
};

/**
 * @alias ActiveRecord.Class.removeIndex
 * @param {String} index_name
 */
ActiveRecord.ClassMethods.removeIndex = function removeIndex(name)
{
    this.stopObserving('afterSave',this.indexingCallbackObservers[name].afterSave);
    this.stopObserving('afterDestroy',this.indexingCallbackObservers[name].afterDestroy);
    delete this.indexingCallbacks[name];
    delete this.indexed[name];
};

ActiveRecord.Indicies = Indicies;<|endoftext|>


<commit_before>import React from 'react';

const StreetView = ({ googleApiToken, streetViewCoordinates, onStreetViewHide }) => {

    let GOOGLE_STREET_VIEW_URL = `https://www.google.com/maps/embed/v1/streetview?key=${googleApiToken}&location=${streetViewCoordinates.lat},${streetViewCoordinates.lng}`

    return (

                <button className="streetview-container--closebutton" onClick={onStreetViewHide}></button>

    )
}

export default StreetView
<commit_msg>Removing ;<commit_after>import React from 'react'

const StreetView = ({ googleApiToken, streetViewCoordinates, onStreetViewHide }) => {

    let GOOGLE_STREET_VIEW_URL = `https://www.google.com/maps/embed/v1/streetview?key=${googleApiToken}&location=${streetViewCoordinates.lat},${streetViewCoordinates.lng}`

    return (

                <button className="streetview-container--closebutton" onClick={onStreetViewHide}></button>

    )
}

export default StreetView
<|endoftext|>


<commit_before>App.Investigation = DS.Model.extend({
  name: DS.attr('string', {defaultValue: 'New investigation'}),
  queryDefinition: DS.attr('string'),
  xAxisLabel: DS.attr('string'),
  yAxisLabel: DS.attr('string'),
  project: DS.belongsTo('project')
});<commit_msg>Add new fields to investigation<commit_after>App.Investigation = DS.Model.extend({
  name: DS.attr('string', {defaultValue: 'New investigation'}),
  queryDefinition: DS.attr('string'),
  xAxisLabel: DS.attr('string'),
  yAxisLabel: DS.attr('string'),
  organization: DS.attr('string'),
  product: DS.attr('string'),
  project: DS.belongsTo('project')
});<|endoftext|>


<commit_before>'use strict';

const getChannelURL = require('ember-source-channel-url');

module.exports = async function() {
  return {
    scenarios: [
      {
        name: 'ember-lts-3.4',
        npm: {
          devDependencies: {
            'ember-source': '~3.4.0'
          }
        }
      },
      {
        name: 'ember-lts-3.8',
        npm: {
          devDependencies: {
            'ember-source': '~3.8.0'
          }
        }
      },
      {
        name: 'ember-release',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('release')
          }
        }
      },
      {
        name: 'ember-beta',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('beta')
          }
        }
      },
      {
        name: 'ember-canary',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('canary')
          }
        }
      },
      // The default `.travis.yml` runs this scenario via `npm test`,
      // not via `ember try`. It's still included here so that running
      // `ember try:each` manually or from a customized CI config will run it
      // along with all the other scenarios.
      {
        name: 'ember-default',
        npm: {
          devDependencies: {}
        }
      }    ]
  };
};
<commit_msg>ember-try config: use yarn<commit_after>'use strict';

const getChannelURL = require('ember-source-channel-url');

module.exports = async function() {
  return {
    useYarn: true,
    scenarios: [
      {
        name: 'ember-lts-3.4',
        npm: {
          devDependencies: {
            'ember-source': '~3.4.0'
          }
        }
      },
      {
        name: 'ember-lts-3.8',
        npm: {
          devDependencies: {
            'ember-source': '~3.8.0'
          }
        }
      },
      {
        name: 'ember-release',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('release')
          }
        }
      },
      {
        name: 'ember-beta',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('beta')
          }
        }
      },
      {
        name: 'ember-canary',
        npm: {
          devDependencies: {
            'ember-source': await getChannelURL('canary')
          }
        }
      },
      // The default `.travis.yml` runs this scenario via `npm test`,
      // not via `ember try`. It's still included here so that running
      // `ember try:each` manually or from a customized CI config will run it
      // along with all the other scenarios.
      {
        name: 'ember-default',
        npm: {
          devDependencies: {}
        }
      }    ]
  };
};
<|endoftext|>


<commit_before>/**
 * Created by Mihail on 12/8/2016.
 */
'use strict';

import React from 'react';
import Button from './Button';
import EventsConsts from '../components/EventsConsts';
import SchemaEmail from '../schema-login-email-form';
import Form from './Form';
import CRUDStore from '../flux/CRUDStore';
import ViewManipulator from '../../utils/view-manipulator';

type State = {
	isLogged: boolean,
};

class Login extends React.Component {
	state: State;

	constructor() {
		super();
		this.state = {
			isLogged: CRUDStore.isLoggedIn()
		};

		Login.login = Login.login.bind(this);

		CRUDStore.addListener(EventsConsts.LOGIN_SUCCESS, () => {
			this.setState({isLogged: true});
			ViewManipulator.toggleErrorMessageView(document.querySelector('#errorMsg'),
				'Wrong login details.', false);
		});

		CRUDStore.addListener(EventsConsts.LOGIN_FAILED, () => {
			this.setState({isLogged: false});
			ViewManipulator.toggleErrorMessageView(document.querySelector('#errorMsg'),
				'Wrong login details.', true);
		});

		CRUDStore.addListener(EventsConsts.LOGOUT, () => {
			this.setState({isLogged: false});
		});
	}

	static login() {
		CRUDStore.checkLogin(this.refs.loginForm.getData());
	}

	render() {
		return

Bingo Bigul Back Office Login

			<Form fields={SchemaEmail} ref="loginForm" />
			<Button onClick={Login.login}>
				Login
			</Button>

				© 2016 Copyrights Mihail Gaberov.

	}
}
export default Login<commit_msg>Update Login.js<commit_after>/**
 * Created by Mihail on 12/8/2016.
 */
'use strict';

import React from 'react';
import Button from './Button';
import EventsConsts from '../components/EventsConsts';
import SchemaEmail from '../schema-login-email-form';
import Form from './Form';
import CRUDStore from '../flux/CRUDStore';
import ViewManipulator from '../../utils/view-manipulator';

type State = {
	isLogged: boolean,
};

class Login extends React.Component {
	state: State;

	constructor() {
		super();
		this.state = {
			isLogged: CRUDStore.isLoggedIn()
		};

		Login.login = Login.login.bind(this);

		CRUDStore.addListener(EventsConsts.LOGIN_SUCCESS, () => {
			this.setState({isLogged: true});
			ViewManipulator.toggleErrorMessageView(document.querySelector('#errorMsg'),
				'Wrong login details.', false);
		});

		CRUDStore.addListener(EventsConsts.LOGIN_FAILED, () => {
			this.setState({isLogged: false});
			ViewManipulator.toggleErrorMessageView(document.querySelector('#errorMsg'),
				'Wrong login details.', true);
		});

		CRUDStore.addListener(EventsConsts.LOGOUT, () => {
			this.setState({isLogged: false});
		});
	}

	static login() {
		CRUDStore.checkLogin(this.refs.loginForm.getData());
	}

	render() {
		return

Bingo Bigul Back Office Login

			<Form fields={SchemaEmail} ref="loginForm" />
			<Button onClick={Login.login}>
				Login
			</Button>

				© 2016{new Date().getFullYear()>2016 && document.write("-"+new Date().getFullYear());} Mihail Gaberov.

	}
}
export default Login
<|endoftext|>


<commit_before>/* eslint indent: ["off"] */
import $ from 'dom7';
import Utils from '../../utils/utils';
import Modal from '../modal/modal-class';

class Actions extends Modal {
  constructor(app, params) {
    const extendedParams = Utils.extend(
      { on: {} },
      app.params.actions,
      params
    );

    // Extends with open/close Modal methods;
    super(app, extendedParams);

    const actions = this;

    actions.params = extendedParams;

    // Buttons
    let groups;
    if (actions.params.buttons) {
      groups = actions.params.buttons;
      if (!Array.isArray(groups[0])) groups = [groups];
    }
    actions.groups = groups;

    // Find Element
    let $el;
    if (actions.params.el) {
      $el = $(actions.params.el);
    } else if (actions.params.content) {
      $el = $(actions.params.content);
    } else if (actions.params.buttons) {
      if (actions.params.convertToPopover) {
        actions.popoverHtml = actions.renderPopover();
      }
      actions.actionsHtml = actions.render();
    }

    if ($el && $el.length > 0 && $el[0].f7Modal) {
      return $el[0].f7Modal;
    }

    if ($el && $el.length === 0 && !(actions.actionsHtml || actions.popoverHtml)) {
      return actions.destroy();
    }

    // Backdrop
    let $backdropEl;
    if (actions.params.backdrop) {
      $backdropEl = app.root.children('.actions-backdrop');
      if ($backdropEl.length === 0) {
        $backdropEl = $('

');
        app.root.append($backdropEl);
      }
    }

    const originalOpen = actions.open;
    const originalClose = actions.close;

    let popover;
    function buttonOnClick(e) {
      const buttonEl = this;
      let buttonIndex;
      let groupIndex;
      if ($(buttonEl).hasClass('item-link')) {
        buttonIndex = $(buttonEl).parents('li').index();
        groupIndex = $(buttonEl).parents('.list').index();
      } else {
        buttonIndex = $(buttonEl).index();
        groupIndex = $(buttonEl).parents('.actions-group').index();
      }
      if (typeof groups != 'undefined') {
        const button = groups[groupIndex][buttonIndex];
        if (button.onClick) button.onClick(actions, e);
        if (actions.params.onClick) actions.params.onClick(actions, e);
        if (button.close !== false) actions.close();
      }
    }
    actions.open = function open(animate) {
      let convertToPopover = false;
      const { targetEl, targetX, targetY, targetWidth, targetHeight } = actions.params;
      if (actions.params.convertToPopover && (targetEl || (targetX !== undefined && targetY !== undefined))) {
        // Popover
        if (
          actions.params.forceToPopover ||
          (app.device.ios && app.device.ipad) ||
          app.width >= 768
        ) {
          convertToPopover = true;
        }
      }
      if (convertToPopover && actions.popoverHtml) {
        popover = app.popover.create({
          content: actions.popoverHtml,
          backdrop: actions.params.backdrop,
          targetEl,
          targetX,
          targetY,
          targetWidth,
          targetHeight,
        });
        popover.open(animate);
        popover.once('popoverOpened', () => {
          popover.$el.find('.item-link').each((groupIndex, buttonEl) => {
            $(buttonEl).on('click', buttonOnClick);
          });
        });
        popover.once('popoverClosed', () => {
          popover.$el.find('.item-link').each((groupIndex, buttonEl) => {
            $(buttonEl).off('click', buttonOnClick);
          });
          Utils.nextTick(() => {
            popover.destroy();
            popover = undefined;
          });
        });
      } else {
        actions.$el = actions.actionsHtml ? $(actions.actionsHtml) : actions.$el;
        actions.$el[0].f7Modal = actions;
        actions.$el.find('.actions-button').each((groupIndex, buttonEl) => {
          $(buttonEl).on('click', buttonOnClick);
        });
        actions.once('actionsClosed', () => {
          actions.$el.find('.list-button').each((groupIndex, buttonEl) => {
            $(buttonEl).off('click', buttonOnClick);
          });
        });
        originalOpen.call(actions, animate);
      }
      return actions;
    };

    actions.close = function close(animate) {
      if (popover) {
        popover.close(animate);
      } else {
        originalClose.call(actions, animate);
      }
      return actions;
    };

    Utils.extend(actions, {
      app,
      $el,
      el: $el ? $el[0] : undefined,
      $backdropEl,
      backdropEl: $backdropEl && $backdropEl[0],
      type: 'actions',
    });

    function handleClick(e) {
      const target = e.target;
      const $target = $(target);
      if ($target.closest(actions.el).length === 0) {
        if (
          actions.params.closeByBackdropClick &&
          actions.params.backdrop &&
          actions.backdropEl &&
          actions.backdropEl === target
        ) {
          actions.close();
        }
      }
    }

    actions.on('opened', () => {
      if (actions.params.closeByBackdropClick) {
        app.on('click', handleClick);
      }
    });
    actions.on('close', () => {
      if (actions.params.closeByBackdropClick) {
        app.off('click', handleClick);
      }
    });

    if ($el) {
      $el[0].f7Modal = actions;
    }

    return actions;
  }
  render() {
    const actions = this;
    if (actions.params.render) return actions.params.render.call(actions, actions);
    const { groups } = actions;
    return `

        ${groups.map(group =>
          `

            ${group.map((button) => {
              const buttonClasses = [`actions-${button.label ? 'label' : 'button'}`];
              const { color, bg, bold, disabled, label, text, icon } = button;
              if (color) buttonClasses.push(`color-${color}`);
              if (bg) buttonClasses.push(`bg-${color}`);
              if (bold) buttonClasses.push('actions-button-bold');
              if (disabled) buttonClasses.push('disabled');
              if (label) {
                return `<div class="${buttonClasses.join(' ')}">${text}</div>`;
              }
              return `

                  ${icon ? `<div class="actions-button-media">${icon}</div>` : ''}

${text}

`.trim();
            }).join('')}

`).join('')}

    `.trim();
  }
  renderPopover() {
    const actions = this;
    if (actions.params.renderPopover) return actions.params.renderPopover.call(actions, actions);
    const { groups } = actions;
    return `

          ${groups.map(group => `

                ${group.map((button) => {
                  const itemClasses = [];
                  const { color, bg, bold, disabled, label, text, icon } = button;
                  if (color) itemClasses.push(`color-${color}`);
                  if (bg) itemClasses.push(`bg-${bg}`);
                  if (bold) itemClasses.push('popover-from-actions-bold');
                  if (disabled) itemClasses.push('disabled');
                  if (label) {
                    itemClasses.push('popover-from-actions-label');
                    return `<li class="${itemClasses.join(' ')}">${text}</li>`;
                  }
                  itemClasses.push('item-link');
                  if (icon) {
                    itemClasses.push('item-content');
                    return `

                            ${icon}

                              ${text}

                    `;
                  }
                  itemClasses.push('list-button');
                  return `

                      ${text}

                  `;
                }).join('')}

          `).join('')}

    `.trim();
  }
}

export default Actions;
<commit_msg>Update actions-class.js<commit_after>/* eslint indent: ["off"] */
import $ from 'dom7';
import Utils from '../../utils/utils';
import Modal from '../modal/modal-class';

class Actions extends Modal {
  constructor(app, params) {
    const extendedParams = Utils.extend(
      { on: {} },
      app.params.actions,
      params
    );

    // Extends with open/close Modal methods;
    super(app, extendedParams);

    const actions = this;

    actions.params = extendedParams;

    // Buttons
    let groups;
    if (actions.params.buttons) {
      groups = actions.params.buttons;
      if (!Array.isArray(groups[0])) groups = [groups];
    }
    actions.groups = groups;

    // Find Element
    let $el;
    if (actions.params.el) {
      $el = $(actions.params.el);
    } else if (actions.params.content) {
      $el = $(actions.params.content);
    } else if (actions.params.buttons) {
      if (actions.params.convertToPopover) {
        actions.popoverHtml = actions.renderPopover();
      }
      actions.actionsHtml = actions.render();
    }

    if ($el && $el.length > 0 && $el[0].f7Modal) {
      return $el[0].f7Modal;
    }

    if ($el && $el.length === 0 && !(actions.actionsHtml || actions.popoverHtml)) {
      return actions.destroy();
    }

    // Backdrop
    let $backdropEl;
    if (actions.params.backdrop) {
      $backdropEl = app.root.children('.actions-backdrop');
      if ($backdropEl.length === 0) {
        $backdropEl = $('

');
        app.root.append($backdropEl);
      }
    }

    const originalOpen = actions.open;
    const originalClose = actions.close;

    let popover;
    function buttonOnClick(e) {
      const buttonEl = this;
      let buttonIndex;
      let groupIndex;
      if ($(buttonEl).hasClass('item-link')) {
        buttonIndex = $(buttonEl).parents('li').index();
        groupIndex = $(buttonEl).parents('.list').index();
      } else {
        buttonIndex = $(buttonEl).index();
        groupIndex = $(buttonEl).parents('.actions-group').index();
      }
      if (typeof groups !== 'undefined') {
        const button = groups[groupIndex][buttonIndex];
        if (button.onClick) button.onClick(actions, e);
        if (actions.params.onClick) actions.params.onClick(actions, e);
        if (button.close !== false) actions.close();
      }
    }
    actions.open = function open(animate) {
      let convertToPopover = false;
      const { targetEl, targetX, targetY, targetWidth, targetHeight } = actions.params;
      if (actions.params.convertToPopover && (targetEl || (targetX !== undefined && targetY !== undefined))) {
        // Popover
        if (
          actions.params.forceToPopover ||
          (app.device.ios && app.device.ipad) ||
          app.width >= 768
        ) {
          convertToPopover = true;
        }
      }
      if (convertToPopover && actions.popoverHtml) {
        popover = app.popover.create({
          content: actions.popoverHtml,
          backdrop: actions.params.backdrop,
          targetEl,
          targetX,
          targetY,
          targetWidth,
          targetHeight,
        });
        popover.open(animate);
        popover.once('popoverOpened', () => {
          popover.$el.find('.item-link').each((groupIndex, buttonEl) => {
            $(buttonEl).on('click', buttonOnClick);
          });
        });
        popover.once('popoverClosed', () => {
          popover.$el.find('.item-link').each((groupIndex, buttonEl) => {
            $(buttonEl).off('click', buttonOnClick);
          });
          Utils.nextTick(() => {
            popover.destroy();
            popover = undefined;
          });
        });
      } else {
        actions.$el = actions.actionsHtml ? $(actions.actionsHtml) : actions.$el;
        actions.$el[0].f7Modal = actions;
        actions.$el.find('.actions-button').each((groupIndex, buttonEl) => {
          $(buttonEl).on('click', buttonOnClick);
        });
        actions.once('actionsClosed', () => {
          actions.$el.find('.list-button').each((groupIndex, buttonEl) => {
            $(buttonEl).off('click', buttonOnClick);
          });
        });
        originalOpen.call(actions, animate);
      }
      return actions;
    };

    actions.close = function close(animate) {
      if (popover) {
        popover.close(animate);
      } else {
        originalClose.call(actions, animate);
      }
      return actions;
    };

    Utils.extend(actions, {
      app,
      $el,
      el: $el ? $el[0] : undefined,
      $backdropEl,
      backdropEl: $backdropEl && $backdropEl[0],
      type: 'actions',
    });

    function handleClick(e) {
      const target = e.target;
      const $target = $(target);
      if ($target.closest(actions.el).length === 0) {
        if (
          actions.params.closeByBackdropClick &&
          actions.params.backdrop &&
          actions.backdropEl &&
          actions.backdropEl === target
        ) {
          actions.close();
        }
      }
    }

    actions.on('opened', () => {
      if (actions.params.closeByBackdropClick) {
        app.on('click', handleClick);
      }
    });
    actions.on('close', () => {
      if (actions.params.closeByBackdropClick) {
        app.off('click', handleClick);
      }
    });

    if ($el) {
      $el[0].f7Modal = actions;
    }

    return actions;
  }
  render() {
    const actions = this;
    if (actions.params.render) return actions.params.render.call(actions, actions);
    const { groups } = actions;
    return `

        ${groups.map(group =>
          `

            ${group.map((button) => {
              const buttonClasses = [`actions-${button.label ? 'label' : 'button'}`];
              const { color, bg, bold, disabled, label, text, icon } = button;
              if (color) buttonClasses.push(`color-${color}`);
              if (bg) buttonClasses.push(`bg-${color}`);
              if (bold) buttonClasses.push('actions-button-bold');
              if (disabled) buttonClasses.push('disabled');
              if (label) {
                return `<div class="${buttonClasses.join(' ')}">${text}</div>`;
              }
              return `

                  ${icon ? `<div class="actions-button-media">${icon}</div>` : ''}

${text}

`.trim();
            }).join('')}

`).join('')}

    `.trim();
  }
  renderPopover() {
    const actions = this;
    if (actions.params.renderPopover) return actions.params.renderPopover.call(actions, actions);
    const { groups } = actions;
    return `

          ${groups.map(group => `

                ${group.map((button) => {
                  const itemClasses = [];
                  const { color, bg, bold, disabled, label, text, icon } = button;
                  if (color) itemClasses.push(`color-${color}`);
                  if (bg) itemClasses.push(`bg-${bg}`);
                  if (bold) itemClasses.push('popover-from-actions-bold');
                  if (disabled) itemClasses.push('disabled');
                  if (label) {
                    itemClasses.push('popover-from-actions-label');
                    return `<li class="${itemClasses.join(' ')}">${text}</li>`;
                  }
                  itemClasses.push('item-link');
                  if (icon) {
                    itemClasses.push('item-content');
                    return `

                            ${icon}

                              ${text}

                    `;
                  }
                  itemClasses.push('list-button');
                  return `

                      ${text}

                  `;
                }).join('')}

          `).join('')}

    `.trim();
  }
}

export default Actions;
<|endoftext|>