All files / widgets/taggable index.js

0% Statements 0/195
0% Branches 0/74
0% Functions 0/48
0% Lines 0/6
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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import css from 'classnames'
import Select from 'react-select'
import Highlighter from 'react-highlight-words'
import TaggableStyled from './taggable.styled'
import { ArrowContent } from 'src'
import InputContainer from 'utils/input-container'
import {
  SmallSuccess,
  SmallAlert,
  SmallBlocked,
  SmallError
} from 'icons'
 
//#region Components
const RemoveIcon = ({ color = "#EC393D" }) => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <g fill={color} fillRule="evenodd">
      <path d="M12 20c-4.411 0-8-3.589-8-8s3.589-8 8-8 8 3.589 8 8-3.589 8-8 8m0-17c-4.962 0-9 4.038-9 9 0 4.963 4.038 9 9 9 4.963 0 9-4.037 9-9 0-4.962-4.037-9-9-9" />
      <path d="M15.854 8.146a.5.5 0 0 0-.707 0l-3.148 3.146-3.146-3.146a.5.5 0 0 0-.707.707l3.146 3.148-3.146 3.146a.5.5 0 0 0 .707.707L12 12.708l3.147 3.146a.498.498 0 0 0 .707 0 .5.5 0 0 0 0-.707L12.707 12l3.146-3.147a.5.5 0 0 0 0-.707" />
    </g>
  </svg>
)
 
const AddIcon = ({ color = "#2870B2" }) => (
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <g fill={color} fillRule="evenodd">
      <path d="M12.5 22C7.262 22 3 17.738 3 12.5S7.262 3 12.5 3 22 7.262 22 12.5 17.738 22 12.5 22zm0-1c4.687 0 8.5-3.813 8.5-8.5C21 7.813 17.187 4 12.5 4 7.813 4 4 7.813 4 12.5c0 4.687 3.813 8.5 8.5 8.5z" />
      <path d="M16.5 13h-8a.5.5 0 1 1 0-1h8a.5.5 0 1 1 0 1z" />
      <path d="M12.5 17a.5.5 0 0 1-.5-.5v-8a.5.5 0 1 1 1 0v8a.5.5 0 0 1-.5.5z" />
    </g>
  </svg>
)
 
const ArrowIcon = ({ color = '#2870B2' }) => (
  <svg xmlns="http://www.w3.org/2000/svg" width="9" height="6" viewBox="0 0 9 6">
    <path fill={color} fillRule="evenodd" d="M1.54 1L4.5 4.7 7.46 1H1.54zM4.5 6a.5.5 0 0 1-.39-.188L.11.813A.502.502 0 0 1 .5 0h8a.5.5 0 0 1 .39.813l-4 4.999A.5.5 0 0 1 4.5 6z" />
  </svg>
)
//#endregion
 
class Taggable extends Component {
  constructor(p) {
    super(p)
 
    this.state = {
      value: undefined,
      listRemove: [],
      active: false
    }
 
    this.cache = {}
    this.timeoutSearch = null
    this.searchTimer = 500
  }
 
  //#region Ações Rest
  search = (parcial = '') => {
    const { providerSearch } = this.props
 
    return new Promise(resolve => {
 
      if (this.timeoutSearch) {
        clearTimeout(this.timeoutSearch)
      }
 
      this.timeoutSearch = setTimeout(() => {
 
        if (parcial in this.cache) {
          resolve({ options: this.cache[parcial] })
        } else {
          providerSearch(parcial).then(data => {
            this.cache[parcial] = data
            resolve({ options: data })
          })
        }
      }, this.searchTimer)
 
    })
  }
 
  create = (item) => {
    const { providerCreate, labelKey, valueKey, multiple, value } = this.props
    const values = item[labelKey].split(/[,|-]/)
 
    if (providerCreate) {
      providerCreate(values).then(options => {
        options.map(option => {
          this.selectComponent.select.selectValue(option)
        })
      })
    }
    else {
      const option = {
        [labelKey]: item[labelKey],
        [valueKey]: item[valueKey]
      }
      this.selectComponent.select.selectValue(option)
    }
  }
 
  remove = (e, option) => {
    e.preventDefault()
    e.stopPropagation()
 
    const { providerRemove, valueKey } = this.props
    const id = `option-${option[valueKey]}`
    const element = document.getElementById(id)
    return providerRemove(option[valueKey]).then((response) => {
      element.classList.add('hide')
      this.setState({
        listRemove: [
          ...this.state.listRemove,
          option
        ]
      })
    })
  }
 
  removeAll = (e, options) => {
    const { providerRemoveAll, valueKey } = this.props
 
    const codigos = options.map(option => option[valueKey])
    providerRemoveAll(codigos).then(res => {
      console.log(res)
    })
  }
 
  //#endregion
 
  //#region Callbacks
  onChange = (value) => {
    const { onChange } = this.props
 
    this.setState({ value }, () => {
      onChange && onChange(value)
    })
  }
 
  onClear = () => {
    const { onClear } = this.props
 
    this.setState({ value: undefined }, () => {
      onClear && onClear()
    })
  }
 
  onValueClick = (valueItem) => {
    const { onValueClick } = this.props
    onValueClick && onValueClick(valueItem)
  }
 
  setActive = (active) => {
    this.setState({ active })
  }
  //#endregion
 
  //#region Methods
  placeholderCreator = (label) => {
    const { placeholderCreator } = this.props
    return placeholderCreator.replace('{label}', label)
  }
 
  setFocus = () => {
    this.selectComponent.focus()
  }
  //#endregion
 
  //#region Renderers
  renderOption = (option, i, selectValue, inFocus = false) => {
    const { labelKey, valueKey } = this.props
    return (
      <div
        key={i}
        id={`option-${option[valueKey]}`}
        className={css({ inFocus: inFocus }, option.className, 'option')}
        onClick={() => selectValue(option)}
      >
        <div className='option-label'>
          <Highlighter searchWords={[this._inputValue]} textToHighlight={option[labelKey]} highlightClassName='text-hightlight' />
        </div>
        <span className='remove-item confirm-remove' onClick={(e) => this.remove(e, option)} >
          <RemoveIcon color='#496072' />
        </span>
        <span className='add-item' >
          <AddIcon />
        </span>
      </div>
    );
  }
 
  menuRenderer = ({ focusedOption, focusOption, options, selectValue, valueArray }) => {
    const { listRemove } = this.state
    const { valueKey } = this.props
 
    return (
      <ArrowContent vAlign='top' hAlign='right' style={{ marginTop: '10px', width: '100%' }}>
        <div className='option-list'>
          {
            options.map((option, i) => {
              if (listRemove.indexOf(option) === -1) {
                return this.renderOption(option, i, selectValue, (option[valueKey] === focusedOption[valueKey]))
              }
            })
          }
          <div className='remove-all' onClick={(e) => this.removeAll(e, options)}>
            <div className='remove-all-label'>Remover Todas</div>
            <span className='remove-all-icon'>
              <RemoveIcon />
            </span>
          </div>
        </div>
      </ArrowContent>
    )
  }
 
  renderStatusIcon () {
    switch (this.props.type) {
      case 'success':
        return <SmallSuccess />
      case 'alert':
        return <SmallAlert />
      case 'blocked':
        return <SmallBlocked />
      case 'error':
        return <SmallError />
      default:
        return null
    }
  };
  //#endregion
 
  render () {
    const { value, active } = this.state
    const {
      type,
      label,
      message,
      showStatusIcon,
      width,
      maxHeight,
      creatable,
      multiple,
      valueKey,
      labelKey,
      filterOptions,
      placeholder,
      placeholderBuscando
    } = this.props
 
    const AsyncComponent = creatable ? Select.AsyncCreatable : Select.Async;
 
    return (
      <InputContainer width={width} type={type} label={label} message={message}>
        <TaggableStyled className={css({ 'active': active })} maxHeight={maxHeight}>
          <div className='async-component' ref={(el) => this.component = el}>
            <AsyncComponent
              onOpen={() => this.setActive(true)}
              onClose={() => this.setActive(false)}
              onInputChange={(inputValue) => this._inputValue = inputValue}
              ref={(el) => this.selectComponent = el}
              loadingPlaceholder={placeholderBuscando}
              promptTextCreator={this.placeholderCreator}
              searchPromptText=''
              backspaceToRemoveMessage=''
              placeholder={placeholder}
              multi={multiple}
              value={value}
              valueKey={valueKey}
              labelKey={labelKey}
              backspaceRemoves={true}
              clearable={false}
              cache={false}
              menuRenderer={this.menuRenderer}
              filterOptions={filterOptions}
              onChange={this.onChange}
              onNewOptionClick={this.create}
              onValueClick={this.onValueClick}
              loadOptions={this.search}
            />
            <span className='status-icon'>
              {/* {(position == 'prefix') && this.renderStatusIcon()} */}
              {(showStatusIcon) && this.renderStatusIcon()}
            </span>
          </div>
        </TaggableStyled>
      </InputContainer>
    )
  }
}
 
Taggable.propTypes = {
  type: PropTypes.oneOf(['success', 'error', 'primary', 'secondary', 'default']),
  width: PropTypes.string,
  maxHeight: PropTypes.string,
  creatable: PropTypes.bool.isRequired,
  multiple: PropTypes.bool.isRequired,
  providerSearch: PropTypes.func.isRequired,
  providerCreate: PropTypes.func.isRequired,
  providerRemove: PropTypes.func.isRequired,
  providerRemoveAll: PropTypes.func.isRequired,
  canCreate: PropTypes.bool,
  canRemove: PropTypes.bool,
  valueKey: PropTypes.string,
  labelKey: PropTypes.string,
  placeholder: PropTypes.string,
  placeholderCreator: PropTypes.string,
  placeholderBuscando: PropTypes.string,
  placeholderBusca: PropTypes.string,
  showStatusIcon: PropTypes.bool
}
 
Taggable.defaultProps = {
  type: 'default',
  creatable: true,
  multiple: false,
  valueKey: "value",
  labelKey: "label",
  canCreate: false,
  canRemove: false,
  placeholder: '',
  placeholderCreator: 'Adicionar "{label}"',
  placeholderBuscando: '',
  placeholderBusca: 'Digite para buscar',
  width: '100%',
  maxHeight: '',
  showStatusIcon: true
}
 
export { Taggable }
export { TaggableExpanded } from './taggable-expanded'