All files / Select Select.js

82.74% Statements 163/197
61.43% Branches 43/70
77.42% Functions 24/31
83.51% Lines 157/188
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 5061x   1x   1x 1x 1x 1x 1x 1x   1x               1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x     76x     19x   19x 19x 4x     19x       19x                         19x 19x 19x       19x 24x 24x         11x         11x       7x 7x     10x 10x 9x                                                   2x 2x   2x 2x           2x           2x 2x 2x         1x 1x 1x       5x 5x   5x   5x 5x 5x         5x 5x     5x 5x       10x   10x 10x 6x     10x       10x 10x       14x 14x 14x 22x 22x     22x       25x 5x 5x   5x 3x   3x   3x 4x 4x     3x               3x 3x 3x 3x     3x 3x       5x 5x   1x 1x 1x                   1x 1x 1x                             3x       440x 44x 44x   44x 44x   44x   44x 13x             44x 29x             44x 2x                   42x                           66x               66x         308x 44x 44x   44x 27x             17x   17x 11x 22x 22x 22x                             5x       17x                         88x 44x   44x   3x                     19x       25x                 308x 44x 44x 44x   69x                                       1x                                     1x                                                                     1x 1x   1x 1x   1x   1x 1x      
import React from 'react'
 
require('@webcomponents/shadydom');
 
import PropTypes from 'prop-types'
import styled from 'styled-components'
import enhanceWithClickOutside from 'react-click-outside'
import uuid from 'uuid';
import SelectAsync from './Async'
import shadowDOM from '../helpers/shadowDOM'
 
import {
  KEY_UP,
  KEY_ESC,
  KEY_DOWN,
  KEY_ENTER,
  KEY_BACKSPACE
} from './constants'
 
const SEARCH_INPUT_MIN_SIZE = 1;
 
import Select from './partials/Select'
import SelectMenu from './partials/SelectMenu'
import SelectValue from './partials/SelectValue'
import SelectMultiValue from './partials/SelectMultiValue'
import SelectClear from './partials/SelectClear'
import SelectArrow from './partials/SelectArrow'
import SelectInput from './partials/SelectInput'
import SelectInputField from './partials/SelectInputField'
import SelectInputFieldSize from './partials/SelectInputFieldSize'
import SelectControl from './partials/SelectControl'
import SelectNoResults from './partials/SelectNoResults'
import SelectClearZone from './partials/SelectClearZone'
import SelectArrowZone from './partials/SelectArrowZone'
import SelectMenuOuter from './partials/SelectMenuOuter'
import SelectPlaceholder from './partials/SelectPlaceholder'
import SelectValueWrapper from './partials/SelectValueWrapper'
import SelectMultiValueWrapper from './partials/SelectMultiValueWrapper'
 
import ValueRenderer from './renderers/ValueRenderer'
import OptionRenderer from './renderers/OptionRenderer'
 
import stringifyValue from './functions/stringifyValue'
 
class WrapperSelect extends React.PureComponent {
  constructor(props) {
    super(props)
 
    this.indexValues(props)
 
    let values = [];
    if (props.value && this.optionsMap.hasOwnProperty(props.value)) {
      values.push(props.value);
    }
 
    Iif (Array.isArray(props.value)) {
      values = values.concat(props.value);
    }
 
    this.state = {
      values: new Set(values),
      isOpened: false,
      isFocused: false,
      isSelected: false,
      searchTerm: null,
      searchWidth: 1,
      focusedIndex: 0,
      options: props.options,
      'aria-owns': this.props['aria-owns'] || uuid.v4(),
      'input-field-id': uuid.v4()
    }
 
    this.inputInnerRef = null
    this.searchSizeRef = null
    this.shouldFireClickOutsideHack = null
  }
 
  indexValues(props) {
    this.optionsMap = props.options.reduce((agregate, current) => {
      agregate[current.value] = current
      return agregate
    }, {})
  }
 
  openOptions() {
    this.setState({
      options: this.getOptions(),
      focusedIndex: 0,
      isOpened: true
    });
    this.props.onOpen();
  }
 
  closeOptions() {
    this.setState({ isOpened: false });
    this.props.onClose();
  }
 
  setFocus() {
    setTimeout(() => {
      this.inputInnerRef && this.inputInnerRef.focus();
    }, 10);
  }
 
  // react-click-outside callback
 
  handleClickOutside(event) {
    if (this.state.isOpened && this.shouldFireClickOutsideHack) {
      this.closeOptions()
      this.shouldFireClickOutsideHack = false
    }
  }
 
  onRemoveTag = (props, e) => {
    e.stopPropagation();
    const { multi } = this.props;
 
    this.state.values.delete(props.value);
 
    this.setState({
      values: new Set(Array.from(this.state.values))
    }, () => {
      this.props.onChange(Array.from(this.state.values));
    });
  }
 
  resetField() {
    const { multi } = this.props;
 
    let values = [];
    Iif (multi) {
      values = Array.from(this.state.values);
      values.pop();
      this.props.onChange(values);
    }
 
    this.setState({
      values: new Set(values),
      searchTerm: null,
      focusedIndex: 0,
      options: this.props.options,
    }, () => {
      this.closeOptions()
      this.inputInnerRef.value = ''
      this.props.onInputClear()
    })
  }
 
  onClearValue = (event) => {
    event.preventDefault()
    event.stopPropagation()
    this.resetField();
  }
 
  onSelectValue = (newValue, event) => {
    const { multi } = this.props;
    const { values } = this.state;
 
    !multi && values.clear(); // when is not multi select
 
    Eif (!values.has(newValue)) {
      values.add(newValue);
      this.setState({
        values,
        searchTerm: null,
        focusedIndex: 0
      }, () => {
        this.inputInnerRef.value = ''
        this.props.onChange(multi ? Array.from(values) : newValue);
      })
    }
    this.closeOptions()
    this.props.onValueClick(multi ? Array.from(values) : newValue, event);
  }
 
  onSelectFocused = (event) => {
    this.shouldFireClickOutsideHack = false
 
    clearInterval(this.focusedTimeout)
    this.focusedTimeout = window.setTimeout(() => {
      this.shouldFireClickOutsideHack = true
    }, 200)
 
    this.setState({
      isFocused: true
    })
 
    this.openOptions();
    this.setFocus();
  }
 
  getOptions() {
    const { multi } = this.props;
    const { values } = this.state;
    return this.props.options.filter((opt) => {
      const label = opt.label.toLowerCase().trim()
      Iif (values.has(label) && multi) {
        return false;
      }
      return true;
    });
  }
 
  onSearching = (event) => {
    const { onInputChange, onTyping } = this.props
    const { focusedIndex, options, isOpened } = this.state;
 
    const typing = () => {
      const term = this.inputInnerRef.value.toLowerCase().trim()
 
      onTyping(term)
 
      const filteredOptions = this.getOptions().filter((opt) => {
        const label = opt.label.toLowerCase().trim()
        return label.indexOf(term) !== -1
      });
 
      this.setState({
        searchTerm: this.inputInnerRef.value,
        searchWidth,
        options: filteredOptions,
        isOpened: true,
        focusedIndex: 0
      })
 
      let searchWidth = SEARCH_INPUT_MIN_SIZE;
      Eif (this.searchSizeRef) {
        const width = this.searchSizeRef.getBoundingClientRect().width;
        searchWidth = width > SEARCH_INPUT_MIN_SIZE ? width : SEARCH_INPUT_MIN_SIZE;
      }
 
      setTimeout(() => {
        this.setState({ searchWidth })
      });
    }
 
    const lastIndex = (options.length - 1)
    switch (event.keyCode) {
      case KEY_BACKSPACE: // backspace
        Eif (!this.inputInnerRef.value) {
          this.resetField();
          break;
        }
        setTimeout(typing, 1);
        break;
      case KEY_UP:
        this.setState({
          focusedIndex: (focusedIndex <= 0 ? lastIndex : (focusedIndex - 1))
        })
        break;
      case KEY_DOWN:
        Eif (!isOpened) {
          this.openOptions();
          break;
        }
        this.setState({
          focusedIndex: (focusedIndex >= lastIndex ? 0 : (focusedIndex + 1))
        })
        break;
      case KEY_ENTER:
        if (!options.length) break;
        const newValue = options[focusedIndex].value
        this.onSelectValue(newValue, event);
        break;
      case KEY_ESC:
        this.closeOptions();
        break;
      default:
        setTimeout(typing, 1);
    }
  }
 
  renderSelectMultiValueWrapper() {
    const { multi, placeholder, searchable, classes, valueRenderer } = this.props;
    const { values, isOpened, isSelected, searchTerm, searchWidth } = this.state;
 
    const SelectValueComp = multi ? SelectMultiValue : SelectValue;
    const SelectWrapperComp = multi ? SelectMultiValueWrapper : SelectValueWrapper;
 
    let content = '';
 
    if (values.size) {
      content = Array.from(values).map((value, key) => (
        <SelectValueComp value={value} onRemoveTag={this.onRemoveTag} key={key} className={classes.selectValue} data-select-value data-multi-value={multi}>
          {valueRenderer({ multi, value, label: this.optionsMap[value].label }, classes.selectValueLabel)}
        </SelectValueComp>
      ));
    }
 
    if (!values.size && !searchTerm) {
      content = (
        <SelectPlaceholder
          className={classes.selectPlaceholder}
          data-select-placeholder>{placeholder}</SelectPlaceholder>
      )
    }
 
    if (!searchable) {
      return (
        <SelectWrapperComp
          for={this.state['input-field-id']}
          className={classes.selectMultiValueWrapper}
          data-select-multi-value-wrapper={multi}>
          {content}
        </SelectWrapperComp>
      );
    }
 
    return (
      <SelectWrapperComp
        for={this.state['input-field-id']}
        className={classes.selectMultiValueWrapper}
        data-select-multi-value-wrapper={multi}>
        {content}
        <SelectInput data-select-input className={classes.selectInput}>
          <SelectInputField
            style={{width: `${searchWidth}px`}}
            id={this.state['input-field-id']}
            className={classes.selectInputField}
            data-select-input-search
            onKeyDown={this.onSearching}
            onChange={this.props.onInputChange}
            innerRef={(n) => this.inputInnerRef = n}
            aria-label={placeholder}
            aria-expanded={isOpened}
            aria-owns={this.state['aria-owns']}
            role="combobox" type="text" />
        </SelectInput>
        <SelectInputFieldSize
          data-select-input-size
          innerRef={(n) => this.searchSizeRef = n}>{searchTerm}</SelectInputFieldSize>
      </SelectWrapperComp>
    );
  }
 
  renderSelectMenuOuter() {
    const { classes, noResultsText, optionRenderer } = this.props;
    const { values, isOpened, focusedIndex, options } = this.state;
 
    if (!isOpened) {
      return (
        <div aria-hidden="true" id={['aria-owns']} role="listbox">
          <div role="option" tabIndex="-1" />
        </div>
      );
    }
 
    let selectOptions = <SelectNoResults>{noResultsText}</SelectNoResults>;
 
    if (options.length > 0) {
      selectOptions = options.map((opt, i) => {
        const isSelected = values.has(opt.value);
        const isFocused = focusedIndex === i;
        return optionRenderer(Object.assign({
          key: i,
          'data-key': i,
          isSelected,
          id: this.state['aria-owns'],
          className: classes.selectOption,
          isFocused: focusedIndex == i,
          tabIndex: values.has(opt.value) ? '0' : '-1',
          onMouseOver: (e) => {
            const dataKey = e.target.getAttribute('data-key');
            this.setState({ focusedIndex: dataKey });
          },
          onMouseOut: (e) => {
            this.setState({ focusedIndex: null });
          },
          onMouseDown: (e) => this.onSelectValue(opt.value, e)
        }, opt), i);
      });
    }
    return (
      <SelectMenuOuter
        className={classes.selectMenuOuter}
        data-select-menu-outer>
        <SelectMenu
          role="listbox"
          className={classes.selectMenu} data-select-menu>
          {selectOptions}
        </SelectMenu>
      </SelectMenuOuter>
    )
  }
 
  renderSelectClearZone() {
    const { clearable, classes } = this.props;
 
    if (!clearable) return;
 
    return (
      <SelectClearZone
        className={classes.selectClearZone}
        data-select-clear-zone onMouseDown={this.onClearValue}>
        <SelectClear
          className={classes.selectClear} data-select-clear>×</SelectClear>
      </SelectClearZone>
    );
  }
 
  componentDidMount() {
    this.props.generatedClassName(this.selectNode.state.generatedClassName);
  }
 
  componentDidUpdate() {
    this.props.generatedClassName(this.selectNode.state.generatedClassName);
  }
 
  componentWillReceiveProps(nextProps) {
    this.setState({
      options: nextProps.options
    }, () => this.indexValues(nextProps))
  }
 
  render () {
    const { name, disabled, className, classes } = this.props;
    const { value, isSelected, isOpened } = this.state;
    return (
      <Select data-select className={className}
        ref={(node) => this.selectNode = node} innerRef={(node) => this.selectInnerRef = node}>
        <input type="hidden" name={name} value={stringifyValue(value)} disabled={disabled} />
        <SelectControl
          isOpened={isOpened}
          aria-haspopup={isOpened}
          className={classes.selectControl}
          data-select-control onMouseDown={this.onSelectFocused}>
          {this.renderSelectMultiValueWrapper()}
          {this.renderSelectClearZone()}
          <SelectArrowZone
            className={classes.selectArrowZone} data-select-arrow-zone>
            <SelectArrow isOpened={isOpened} className={classes.selectArrow} data-select-arrow />
          </SelectArrowZone>
        </SelectControl>
        {this.renderSelectMenuOuter()}
      </Select>
    )
  }
}
 
WrapperSelect.propTypes = {
  value: PropTypes.any,
  options: PropTypes.array,
  onClose: PropTypes.func,
  onOpen: PropTypes.func,
  onChange: PropTypes.func,
  onValueClick: PropTypes.func,
  onInputClear: PropTypes.func,
  clearable: PropTypes.bool,
  placeholder: PropTypes.string,
  className: PropTypes.string,
  classes: PropTypes.object,
  noResultsText: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.element
  ]),
  generatedClassName: PropTypes.func
}
 
WrapperSelect.defaultProps = {
  onClose: () => {},
  onOpen: () => {},
  onChange: () => {},
  onInputChange: () => {},
  onTyping: () => {},
  onValueClick: () => {},
  onInputClear: () => {},
  clearable: false,
  searchable: true,
  multi: false,
  options: [],
  placeholder: 'Select...',
  noResultsText: 'No results found',
  classes: {
    selectArrow: '',
    selectArrowZone: '',
    selectClear: '',
    selectClearZone: '',
    selectControl: '',
    selectInput: '',
    selectInputField: '',
    selectMenu: '',
    selectMenuOuter: '',
    selectMultiValueWrapper: '',
    selectOption: '',
    selectPlaceholder: '',
    selectValue: '',
    selectValueLabel: ''
  },
  valueRenderer: ValueRenderer,
  optionRenderer: OptionRenderer,
  generatedClassName: () => {}
}
 
const EnhanceWrapperSelect = enhanceWithClickOutside(WrapperSelect)
const ShadowWrapperSelect = shadowDOM(EnhanceWrapperSelect)
 
const NormalAsync = props => <SelectAsync {...props}><EnhanceWrapperSelect /></SelectAsync>
const ShadowAsync = props => <SelectAsync {...props}><ShadowWrapperSelect /></SelectAsync>
 
ShadowWrapperSelect.Async = ShadowAsync
 
export const Async  = EnhanceWrapperSelect.Async = NormalAsync
export const ShadowDOM = EnhanceWrapperSelect.ShadowDOM = ShadowWrapperSelect
 
export default EnhanceWrapperSelect