All files / ship-components-tag-input/src TagContainer.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 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558                                                  30x 30x             30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x       30x 30x   30x 29x         9x                           1x 1x   1x 1x                   3x   1x     2x       2x     2x 2x   2x                   3x   3x 1x     3x     3x 2x     2x   2x         1x                       3x 3x   3x 1x     2x 2x 2x             3x           3x   3x 3x                     1x 1x   1x 1x                                                   4x 4x   1x 1x 1x                           1x 1x 1x   1x   1x 1x       1x 1x   1x 1x   4x             44x 1x     43x         43x     43x 29x                                       2x   2x       2x   2x 4x 4x     2x 1x   1x 1x                 2x 2x   2x     2x 4x 4x     2x 1x   1x   1x                 4x       4x               9x 9x   9x 26x   26x 23x     3x 3x                           95x 95x     95x 4x         95x 7x 7x 7x                                 95x 158x     158x       158x 156x   2x                           137x 136x   1x         89x       89x 89x   89x                                                                                                                                     2x                         2x                                                          
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { Utils } from 'ship-components-utility';
import icon from 'ship-components-icon';
import { List } from 'immutable';
 
import Dropdown from './Dropdown';
import SelectControls from './Controls';
 
import css from './TagContainer.css';
 
/**
 * Filterable Select Dropdown Component
 *
 *   options should be Array<Object> with object fields:
 *   key
 *   title
 *   body
 *   icon (optional node)
 *   optionGroup (optional string)
 *   className (optional string)
 */
export default class TagContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filterText: '',
      dropdownOpen: false,
      empty: this.isEmpty.call(this),
      dropdownPosTop: '53px'
    };
 
    this.selectHighlightedItem = this.selectHighlightedItem.bind(this);
    this.highlightPreviousItem = this.highlightPreviousItem.bind(this);
    this.highlightNextItem = this.highlightNextItem.bind(this);
    this.handleDropdownPosition = this.handleDropdownPosition.bind(this);
    this.getVisibleOptions = this.getVisibleOptions.bind(this);
    this.handleOpenDropdown = this.handleOpenDropdown.bind(this);
    this.focusInput = this.focusInput.bind(this);
    this.blurInput = this.blurInput.bind(this);
    this.clearItem = this.clearItem.bind(this);
    this.optionWasSelected = this.optionWasSelected.bind(this);
    this.documentClickHandler = this.documentClickHandler.bind(this);
    this.isEmpty = this.isEmpty.bind(this);
    this.handleToggleDropdown = this.handleToggleDropdown.bind(this);
    this.handleSelectItem = this.handleSelectItem.bind(this);
    this.handleKeyboard = this.handleKeyboard.bind(this);
    this.handleInput = this.handleInput.bind(this);
    this.handleClearItem = this.handleClearItem.bind(this);
    this._toggleSwitch = this._toggleSwitch.bind(this);
  }
 
  componentDidMount() {
    this.handleDropdownPosition();
    document.addEventListener('click', this.documentClickHandler);
 
    if (this.refs.selectControls) {
      this._inputField = this.refs.selectControls.refs.filterInput;
    }
  }
 
  componentWillReceiveProps(nextProps) {
    this.setState({
      empty: this.isEmpty(nextProps)
    }, this.handleDropdownPosition);
  }
 
  componentWillUnmount() {
    document.removeEventListener('click', this.documentClickHandler);
  }
 
  /**
   * Toggle the options dropdown
   * @param  {Event} event
   */
  handleToggleDropdown(event) {
    event.preventDefault();
    const { dropdownOpen } = this.state;
 
    Eif (!dropdownOpen) {
      this.handleOpenDropdown(event);
    } else {
      this.setState({ dropdownOpen: false });
    }
  }
 
  /**
   * Opens the options dropdown
   */
  handleOpenDropdown(event) {
    if (this.state.dropdownOpen) {
      // dropdown is already open
      return;
    }
 
    Iif (this.props.autoComplete && this.state.filterText.length > 2) {
      this.props.onFetchOptions(null, this.state.dropdownOpen);
    }
 
    this.setState({ dropdownOpen: true },
      () => {
        // time out because of css transitions.
        setTimeout(this.handleDropdownPosition, this.props.transitionDelay);
        this.focusInput();
      });
    Iif (typeof this.props.onFocus === 'function') {
      this.props.onFocus(event);
    }
  }
 
  /**
   * On input, update state: filterText, highlighed item
   * @param  {Event}  event
   */
  handleInput(event) {
    let filterText = event.target.value;
 
    if (this.props.autoComplete && filterText.length > 2) {
      this.props.onFetchOptions(filterText);
    }
 
    this.setState({
      filterText: filterText
    });
    if (filterText.length > 2) {
      this.setState({
        dropdownOpen: true
      }, () => {
        this.handleDropdownPosition();
 
        Iif (typeof this.props.onFilter === 'function') {
          this.props.onFilter(filterText, event);
        }
      });
    } else {
      this.setState({
        dropdownOpen: false
      });
    }
  }
 
  /**
   * Handler for user choosing an option from dropdown
   * @param  {Item}   option  the target option
   * @param  {Event}  event the click or keyboard event
   */
  handleSelectItem(option, event) {
    event.preventDefault();
    event.stopPropagation();
 
    if (!option) {
      return;
    }
 
    const selectionCopy = Utils.deepCopy(option);
    this.props.onSelect(selectionCopy);
    this.optionWasSelected();
  }
 
  /**
   * Peripheral tasks to handleSelectItem
   */
  optionWasSelected() {
    this.setState({
      filterText: this.props.multiple ? '' : this.state.filterText,
      empty: false,
      dropdownOpen: false,
      highlightedOption: null
    }, () => {
      this.handleDropdownPosition();
 
      Eif (this.props.multiple) {
        this.focusInput();
      }
    });
  }
 
  /**
   * Remove an item from the selection
   * @param  {Item}   item  the target item
   * @param  {Event}  event
   */
  handleClearItem(item, event) {
    event.preventDefault();
    event.stopPropagation();
 
    Eif (typeof this.props.onDeselect === 'function') {
      this.props.onDeselect(item, this.clearItem);
    } else {
      //note: this will not work properly as is. need to manually update state.selection
      this.clearItem();
    }
  }
 
  /**
   * Peripheral tasks to handleClearitem
   */
  clearItem() {
    this.setState({
      empty: this.props.selection.length === 0
    }, () => {
      this.handleDropdownPosition();
 
      if (this.props.multiple) {
        this.focusInput();
      }
    });
  }
 
  /**
   * Keyboard shortcuts (select item, close dropdown)
   */
  handleKeyboard(event) { // eslint-disable-line complexity
    let code = event.keyCode || event.which;
    switch (code) {
      case 13: // enter
        Eif (!(this.state.highlightedOption && this.state.dropdownOpen) && typeof this.props.onEnterKey === 'function') {
          this.props.onEnterKey(event);
          break;
        }
        event.preventDefault();
        this.selectHighlightedItem(event);
        break;
      // Commented this out to fix the behavior of the tab key.
      // The tab keyboard event was being used to select a highlighted dropdown option. 
      // This prevented tabbing through components in a modal form dialog.
      // With this change tag - input will ignore tab keyboard events.
      // case 9: // tab
      //   event.preventDefault();
      //   this.selectHighlightedItem(event);
      //   break;
      case 38: // up
        event.preventDefault();
        Eif (this.state.dropdownOpen) {
          this.highlightPreviousItem();
        }
        break;
      case 40: // down
        Eif (!this.state.dropdownOpen) {
          this.setState({
            dropdownOpen: true
          });
        }
        this.highlightNextItem();
        break;
      case 27: // escape
        this.setState({ dropdownOpen: false }, this.blurInput);
        break;
    }
    event.stopPropagation();
  }
 
  /**
   * Determines the `top` css property for the dropdown
   */
  handleDropdownPosition() {
    if (!this.refs.selectBox) {
      return;
    }
 
    Iif (this.props.invert) {
      this.setState({ dropdownPosTop: '53px' });
      return;
    }
 
    let selectBoxHeight = (this.refs.selectBox.offsetHeight) + 'px';
 
    // compare strings
    if (selectBoxHeight !== this.state.dropdownPosTop) {
      this.setState({ dropdownPosTop: selectBoxHeight });
    }
  }
 
  /**
   * Selects the currently highlighted item
   * @param  {Event} event
   */
  selectHighlightedItem(event) {
    let highlightedItem = this.state.highlightedOption;
 
    if (highlightedItem) {
      this.handleSelectItem(highlightedItem, event);
    }
  }
 
  /**
   * Highlights one item up in dropdown; meant to be triggered by user pressing `up arrow` key.
   */
  highlightPreviousItem() {
    let highlightedOption = this.state.highlightedOption;
 
    Iif (!highlightedOption) {
      return;
    }
 
    let options = this.getVisibleOptions();
 
    let currentIndex = options.findIndex((option) => {
      let selector = option.key ? 'key' : this.props.orderOptionsBy;
      return option[selector] === highlightedOption[selector];
    });
 
    if (currentIndex === 0) {
      return;
    }
    highlightedOption = options[currentIndex - 1];
    this.setState({
      highlightedOption: highlightedOption
    });
  }
 
  /**
   * Highlights one item down in dropdown; meant to be triggered by user pressing `down arrow` key.
   */
  highlightNextItem() {
    let highlightedOption = this.state.highlightedOption;
    let options = this.getVisibleOptions();
 
    Iif (!highlightedOption) {
      highlightedOption = options[0];
    } else {
      let currentIndex = options.findIndex((option) => {
        let selector = option.key ? 'key' : this.props.orderOptionsBy;
        return option[selector] === highlightedOption[selector];
      });
 
      if (currentIndex === options.length - 1) {
        return;
      }
      highlightedOption = options[currentIndex + 1];
    }
    this.setState({
      highlightedOption: highlightedOption
    });
  }
 
  /**
   * Focus cursor on filter input
   */
  focusInput() {
    Iif (!this.refs.selectControls) {
      return;
    }
 
    this.refs.selectControls.focusInput();
  }
 
  blurInput() {
    this.refs.selectControls.blurInput();
  }
 
  getFilterResults(filterText) {
    const { options, orderOptionsBy } = this.props;
    const regex = new RegExp(filterText, 'i');
 
    return options.filter((option) => {
      const orderOptionsByType = typeof option[orderOptionsBy];
 
      if (orderOptionsByType === 'string') {
        return regex.test(option[orderOptionsBy].toLowerCase());
      }
 
      Eif (orderOptionsByType === 'number') {
        return option[orderOptionsBy] === Number(filterText);
      }
 
      // In case searching through an object
      return option[orderOptionsBy].hasOwnProperty(filterText);
    });
  }
 
  /**
   * Determines what options to show in dropdown
   * @param  {string}       filterText
   * @return {Array<Option>}  options matching `filterText` and not already selected
   */
  getVisibleOptions(filterText) {
    filterText = typeof filterText === 'undefined' ? this.state.filterText : filterText;
    let options = this.props.options;
 
    // show filtered results
    if (filterText !== '' && !this.props.autoComplete) {
      options = this.getFilterResults(filterText);
    }
 
    // exclude selected options
    // TODO : its probably better (in single-select cases) to show the selected item in the dropdown with a checkmark, similar to standard <select />
    if (!this.isEmpty()) {
      Eif (List.isList(this.props.selection)) {
        Eif (this.props.selection.size > 0) {
          options = options.filter((item) => {
            let selector = item.key ? 'key' : this.props.orderOptionsBy;
            let index = this.props.selection.findIndex(selectedOption => selectedOption[selector] === item[selector]);
            return index < 0;
          });
        }
      } else {
        options = options.filter(item => item.key !== this.props.selection.key);
      }
    }
 
    /**
     * Sort by:
     * 1 - "optionGroup"
     * 2 - "score" if possible
     * 3 - props.orderOptionsBy field
     */
    return options.sort((a, b) => { // eslint-disable-line complexity
      Iif (a.optionGroup !== b.optionGroup) {
        return a.optionGroup > b.optionGroup ? 1 : -1;
      }
      Iif (a.score && b.score && a.score !== b.score) {
        // lower score = closer match (Fuse.js)
        return a.score > b.score ? 1 : -1;
      }
      if (typeof a[this.props.orderOptionsBy] === 'string') {
        return a[this.props.orderOptionsBy].replace(/\s\s+/g, ' ').toLowerCase() > b[this.props.orderOptionsBy].replace(/\s\s+/g, ' ').toLowerCase() ? 1 : -1;
      }
      return a[this.props.orderOptionsBy] > b[this.props.orderOptionsBy] ? 1 : -1;
    });
  }
 
  documentClickHandler(event) {
    if (event.defaultPrevented) {
      return;
    }
    this.setState({
      dropdownOpen: false
    });
  }
 
  isEmpty(props = this.props) {
    if (List.isList(props.selection)) {
      return props.selection.size === 0;
    } else {
      return !props.selection;
    }
  }
 
  _toggleSwitch() {
    return <i className={classNames(icon[this.props.toggleSwitchStyle], css.toggleBtn)} />;
  }
 
  render() {
    const toggleSwitch = this._toggleSwitch();
    let options = this.getVisibleOptions();
 
    return (
      <div
        ref='selectBox'
        onClick={(event) => {
          event.preventDefault();
          event.stopPropagation();
        }}
        className={classNames(
          {
            [css.dropdownOpen]: this.state.dropdownOpen,
            [css.empty]: this.state.empty,
            [css.darkTheme]: this.props.darkTheme
          },
          css.container,
          this.props.className)}
      >
        {this.props.label ?
          <label className={classNames(css.label,
            {
              [css.offset]: !this.state.empty || this.state.dropdownOpen || this.state.filterText,
              [css.darkTheme]: this.props.darkTheme,
              [css.notFilterable]: !this.props.filterable,
              [css.toggleRightPos]: this.props.togglePosition === 'right',
              [css.toggleLeftPos]: this.props.togglePosition === 'left'
            })}
          >
            {this.props.label}
          </label> : null}
 
        <SelectControls
          {...this.props}
          label=''
          ref='selectControls'
          waiting={this.state.waiting}
          isDropdownOpen={this.state.dropdownOpen}
          isEmpty={this.state.empty}
          filterText={this.state.filterText}
          toggleSwitch={toggleSwitch}
          onToggle={this.handleToggleDropdown}
          onChange={this.handleInput}
          onClear={this.handleClearItem}
          onKeyDown={this.handleKeyboard}
          onFocus={this.handleOpenDropdown}
        />
 
        <Dropdown
          {...this.props}
          style={{ top: this.state.dropdownPosTop }}
          filterText={this.state.filterText}
          open={this.state.dropdownOpen}
          highlightedOption={this.state.highlightedOption}
          options={options}
          onKeyDown={this.handleKeyboard}
          onSelect={this.handleSelectItem}
        />
 
        {this.props.noOptionsMessage ?
          <label className={css.error}>
            {this.props.noOptionsMessage}
          </label> : null}
 
      </div>
    );
  }
}
 
// default props
TagContainer.defaultProps = {
  autoComplete: false,
  className: '',
  transitionDelay: 250,
  invert: false,
 
  onFilter: void 0,
  onFocus: void 0,
  onEnterKey: void 0,
  onFetchOptions: void 0
};
 
// prop types checking
TagContainer.propTypes = {
  multiple: PropTypes.bool.isRequired,
  filterable: PropTypes.bool.isRequired,
  darkTheme: PropTypes.bool.isRequired,
  autoComplete: PropTypes.bool,
  invert: PropTypes.bool,
 
  className: PropTypes.string,
  orderOptionsBy: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  togglePosition: PropTypes.string.isRequired,
  noOptionsMessage: PropTypes.string.isRequired,
  toggleSwitchStyle: PropTypes.string.isRequired,
  fetchUrl: PropTypes.string.isRequired,
  fetchOptions: PropTypes.func.isRequired,
 
  options: PropTypes.array.isRequired,
  selection: PropTypes.instanceOf(List).isRequired,
  optionGroupTitles: PropTypes.array.isRequired,
 
  transitionDelay: PropTypes.number,
 
  onFilter: PropTypes.func,
  onFocus: PropTypes.func,
  onSelect: PropTypes.func.isRequired,
  onDeselect: PropTypes.func.isRequired,
  onEnterKey: PropTypes.func,
  onFetchOptions: PropTypes.func
};