All files / ship-components-tag-input/src index.js

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202                    7x 7x         7x 7x 7x       1x                         3x   3x       3x     3x                       2x   2x 2x     2x   2x 1x       2x       1x         1x 1x                                                                                                 9x   9x                             1x                                                         1x                                                      
import React from 'react';
import PropTypes from 'prop-types';
import { List } from 'immutable';
import Promise from 'bluebird';
import superagent from 'superagent';
 
import TagContainer from './TagContainer';
 
export default class TagInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      waiting: false,
      data: props.options
    };
 
    this.handleSelectItem = this.handleSelectItem.bind(this);
    this.handleDeselectItem = this.handleDeselectItem.bind(this);
    this.handleFetchOptions = this.handleFetchOptions.bind(this);
  }
 
  componentWillReceiveProps(nextProps) {
    this.setState({
      data: nextProps.options
    });
  }
 
  /**
   * Selects an item
   * pass it to parent (If any)
   *
   * @param {any} item
   * @memberof TagInput
   */
  handleSelectItem(item) {
    let { value } = this.props;
 
    Iif (!this.props.multiple && !value.size == 0) {
      // clear existing selection and send the tags to parent
      this.props.onChange(new List().push(item));
    } else {
      value = this.props.invert ? value.unshift(item) : value = value.push(item);
 
      // Sending the tags to parent
      this.props.onChange(value);
    }
  }
 
  /**
   * Deselects an item
   * pass it to parent (If any)
   *
   * @param {any} item
   * @memberof TagInput
   */
  handleDeselectItem(item) {
    let { value, selectItemBy } = this.props;
 
    Eif (typeof selectItemBy === 'undefined') {
      selectItemBy = item.key ? 'key' : 'id';
    }
 
    const index = this.props.value.findIndex(selectedItem => item[selectItemBy] === selectedItem[selectItemBy]);
 
    if (index > -1) {
      value = value.splice(index, 1);
    }
 
    // Sending the tags to parent
    this.props.onChange(value);
  }
 
  fetchOptions(query) {
    this.setState({
      waiting: true
    });
 
    // do a user-provided fetch
    Eif (typeof this.props.fetchOptions === 'function') {
      return this.props.fetchOptions(query);
    }
 
    // do a fetch with user-provided url + headers
    const { fetchUrl, httpHeaders } = this.props;
    return new Promise((resolve, reject) => {
      let req = superagent.get(fetchUrl);
      // Setting the http headers
      Object.keys(httpHeaders).forEach((key) => {
        req.set(key, httpHeaders[key]);
      });
 
      req
        .accept('application/json')
        .query({ query: query })
        .end((err, res) => {
          if (err) {
            reject(err);
          }
          resolve(res.body);
        });
    });
  }
 
  handleFetchOptions(query = '', dropdownOpen = false) {
    if (dropdownOpen || this.state.data.some(field => field.label === query)) {
      return;
    }
 
    this.fetchOptions(query)
      .then((res) => {
        this.setState({
          data: this.props.extractor(res)
        });
      })
      .catch((err) => {
        console.error(err);
      })
      .finally(() => {
        this.setState({
          waiting: false
        });
      });
  }
 
  render() {
    const {
      data,
      waiting
    } = this.state;
 
    return (
      <TagContainer
        {...this.props}
        options={data}
        loading={waiting}
        selection={this.props.value}
        onSelect={this.handleSelectItem}
        onDeselect={this.handleDeselectItem}
        onFetchOptions={this.handleFetchOptions}
      />
    );
  }
}
 
// default props
TagInput.defaultProps = {
  loading: false,
  multiple: true,
  filterable: true,
  darkTheme: false,
  invert: false,
 
  className: '',
  orderOptionsBy: 'title',
  label: 'Select Tags...',
  togglePosition: 'left',
  noOptionsMessage: '',
  toggleSwitchStyle: 'search',
  selectItemBy: undefined,
  fetchUrl: '',
  fetchOptions: void 0,
 
 
  optionGroupTitles: [],
  options: [],
 
  httpHeaders: {},
  value: new List(),
 
  onFetchOptions: void 0,
  extractor: data => data
};
 
// prop types checking
TagInput.propTypes = {
  loading: PropTypes.bool,
  multiple: PropTypes.bool,
  filterable: PropTypes.bool,
  darkTheme: PropTypes.bool,
 
  className: PropTypes.string,
  orderOptionsBy: PropTypes.string,
  label: PropTypes.string,
  togglePosition: PropTypes.oneOf(['right', 'left']),
  noOptionsMessage: PropTypes.string,
  toggleSwitchStyle: PropTypes.string,
  selectItemBy: PropTypes.string,
  fetchUrl: PropTypes.string,
  fetchOptions: PropTypes.func,
  invert: PropTypes.bool,
 
  options: PropTypes.array,
  optionGroupTitles: PropTypes.array,
 
  httpHeaders: PropTypes.object,
  value: PropTypes.instanceOf(List).isRequired,
 
  onChange: PropTypes.func.isRequired,
  onFetchOptions: PropTypes.func,
  extractor: PropTypes.func
};