All files / molecule/autosuggest/src index.js

44.21% Statements 42/95
28.2% Branches 22/78
30.76% Functions 4/13
46.66% Lines 42/90

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                              1x                                           17x 17x   17x   17x 17x 17x         17x   17x 2x   2x   2x 2x     2x     17x     58x 58x           17x                   17x                       17x           17x 8x 8x 8x 8x 8x   8x 8x   8x 8x     8x                         17x         17x                                             17x               17x       17x             17x               17x                                             17x       17x                                   1x                                                                                                                                                                                                                                 1x            
import {Children, cloneElement, createRef, useRef, useState} from 'react'
 
import cx from 'classnames'
import PropTypes from 'prop-types'
 
import {getCurrentElementFocused} from '@s-ui/js/lib/dom'
import {getTarget} from '@s-ui/js/lib/react'
import {inputShapes, inputTypes} from '@s-ui/react-atom-input'
import useControlledState from '@s-ui/react-hooks/lib/useControlledState'
import useMergeRefs from '@s-ui/react-hooks/lib/useMergeRefs'
import {moleculeDropdownListSizes as SIZES} from '@s-ui/react-molecule-dropdown-list'
 
import MoleculeAutosuggestMultipleSelection from './components/MultipleSelection/index.js'
import MoleculeAutosuggestSingleSelection from './components/SingleSelection/index.js'
import {
  AUTOSUGGEST_STATES,
  BASE_CLASS,
  CLASS_DISABLED,
  CLOSE_KEYS_LIST,
  getIsTypeableKey,
  SELECT_KEYS_LIST
} from './config.js'
 
const MoleculeAutosuggest = ({
  autoClose = true,
  children,
  disabled,
  errorState,
  id = '',
  isOpen,
  keysCloseList = CLOSE_KEYS_LIST,
  keysSelection = SELECT_KEYS_LIST,
  multiselection,
  onBlur,
  onChange,
  onClear,
  onEnter,
  onFocus,
  onSelect,
  onToggle,
  refMoleculeAutosuggest: refMoleculeAutosuggestFromProps = {},
  refMoleculeAutosuggestInput: refMoleculeAutosuggestInputFromProps = {},
  state,
  ...restProps
}) => {
  const innerRefMoleculeAutosuggest = useRef()
  const refMoleculeAutosuggest = useMergeRefs(innerRefMoleculeAutosuggest, refMoleculeAutosuggestFromProps)
 
  const [isOpenState, setIsOpenState, isControlled] = useControlledState(isOpen, !!isOpen)
 
  const refsMoleculeAutosuggestOptions = useRef([])
  const innerRefMoleculeAutosuggestInput = useRef()
  const refMoleculeAutosuggestInput = useMergeRefs(
    innerRefMoleculeAutosuggestInput,
    refMoleculeAutosuggestInputFromProps
  )
 
  const [focus, setFocus] = useState(false)
 
  const handleToggle = (ev, {isOpen: nextIsOpenState}) => {
    const {type} = ev
 
    Iif (type !== 'change') {
      setIsOpenState(nextIsOpenState, autoClose !== false)
    } else Eif (!isOpenState) {
      setIsOpenState(nextIsOpenState, nextIsOpenState && isOpen !== false)
    }
 
    typeof onToggle === 'function' && onToggle(ev, {isOpen: nextIsOpenState})
  }
 
  const extendedChildren = Children.toArray(children)
    .filter(Boolean)
    .map((child, index) => {
      refsMoleculeAutosuggestOptions.current[index] = createRef()
      return cloneElement(child, {
        innerRef: refsMoleculeAutosuggestOptions.current[index],
        selectKey: keysSelection
      })
    })
 
  const className = cx(
    BASE_CLASS,
    errorState && `${BASE_CLASS}--${AUTOSUGGEST_STATES.ERROR}`,
    errorState === false && `${BASE_CLASS}--${AUTOSUGGEST_STATES.SUCCESS}`,
    state && `${BASE_CLASS}--${state}`,
    {
      [CLASS_DISABLED]: disabled
    }
  )
 
  const closeList = ev => {
    const {current: domMoleculeAutosuggest} = innerRefMoleculeAutosuggest
    handleToggle(ev, {isOpen: false})
    if (multiselection && typeof onChange === 'function') {
      onChange(ev, {value: ''})
    }
    domMoleculeAutosuggest && !focus && domMoleculeAutosuggest.focus()
    setFocus(false)
    ev.preventDefault()
    ev.stopPropagation()
  }
 
  const focusFirstOption = (ev, {options}) => {
    if (options[0]) options[0].focus()
    ev.preventDefault()
    ev.stopPropagation()
  }
 
  const handleKeyDown = ev => {
    ev.persist()
    const {current: domInnerInput} = refMoleculeAutosuggestInput
    const {current: optionsFromRef} = refsMoleculeAutosuggestOptions
    const {key} = ev
    const options = optionsFromRef.map(getTarget)
 
    const isTypeableKey = getIsTypeableKey(key)
    const isSelectionKey = keysSelection.includes(key)
 
    Eif (isTypeableKey) {
      Iif (!isSelectionKey && domInnerInput) domInnerInput.focus()
    }
 
    Iif (isOpenState) {
      const currentElementFocused = getCurrentElementFocused()
      const isSomeOptionFocused = [...options].includes(currentElementFocused)
      if (keysCloseList.includes(key)) closeList(ev)
      else if (key === 'ArrowDown' && !isSomeOptionFocused) focusFirstOption(ev, {options})
      else if (isSomeOptionFocused) handleFocusIn(ev)
      if (key === 'Enter') {
        typeof onEnter === 'function' && onEnter(ev)
        handleFocusInput()
      }
    }
  }
 
  const handleFocusIn = ev => {
    typeof onFocus === 'function' && onFocus(ev)
    setFocus(true)
  }
 
  const handleFocusOut = ev => {
    ev.persist()
    const {current: domContainer} = innerRefMoleculeAutosuggest
    const {current: domInnerInput} = innerRefMoleculeAutosuggestInput
    const {current: optionsFromRef} = refsMoleculeAutosuggestOptions
    const options = optionsFromRef.map(getTarget)
 
    setTimeout(() => {
      const currentElementFocused = getCurrentElementFocused()
      const focusOutFromOutside =
        ![domInnerInput, ...options].includes(currentElementFocused) && !domContainer.contains(currentElementFocused)
      if (focusOutFromOutside) {
        if (autoClose && isOpenState) {
          closeList(ev)
        } else {
          setFocus(false)
        }
        typeof onBlur === 'function' && onBlur()
      }
    }, 1)
    setFocus(true)
  }
 
  const handleInputKeyDown = ev => {
    const {key} = ev
    if (key === 'Enter') {
      typeof onEnter === 'function' && onEnter(ev)
      onEnter && typeof onEnter === 'function' && autoClose && closeList(ev)
    }
  }
 
  const handleClick = () => {
    handleFocusInput()
  }
 
  const handleFocusInput = () => {
    const {current: innerRefInput} = innerRefMoleculeAutosuggestInput
    if (innerRefInput && (!isControlled || autoClose)) {
      innerRefInput.focus()
    }
  }
 
  const handleClear = ev => {
    ev.stopPropagation()
    handleFocusInput()
    if (onClear) {
      onClear(ev)
    }
  }
 
  const autosuggestSelectionProps = {
    autoClose,
    children: extendedChildren,
    disabled,
    errorState,
    id,
    innerRefInput: refMoleculeAutosuggestInput,
    isOpen: isOpenState,
    keysCloseList,
    keysSelection,
    onBlur,
    onChange,
    onClear: handleClear,
    onEnter,
    onFocus,
    onInputKeyDown: handleInputKeyDown,
    onKeyDown: handleKeyDown,
    onSelect,
    onToggle: handleToggle,
    state,
    ...restProps
  }
 
  const AutosuggestSelection = multiselection
    ? MoleculeAutosuggestMultipleSelection
    : MoleculeAutosuggestSingleSelection
 
  return (
    <div
      ref={refMoleculeAutosuggest}
      tabIndex="0"
      className={className}
      onKeyDown={handleKeyDown}
      onFocus={handleFocusIn}
      onBlur={handleFocusOut}
      onClick={handleClick}
      role="combobox"
      aria-controls={id}
      aria-expanded={isOpenState}
    >
      <AutosuggestSelection {...autosuggestSelectionProps} />
    </div>
  )
}
 
MoleculeAutosuggest.propTypes = {
  /** Auto close suggestion list. */
  autoClose: PropTypes.bool,
 
  /** children */
  children: PropTypes.any,
 
  /** if the component is disabled or not */
  disabled: PropTypes.bool,
 
  /** true = error, false = success, null = neutral */
  errorState: PropTypes.bool,
 
  /** Icon for clearing values */
  iconClear: PropTypes.node,
 
  /** Icon for closing (removing) tags */
  iconCloseTag: PropTypes.node,
 
  /** The DOM id global attribute. */
  id: PropTypes.string,
 
  /** To select input keyboard mode on mobile. It can be 'numeric', 'decimal', 'email', etc */
  inputMode: PropTypes.string,
 
  /** if list of options is displayed or not */
  isOpen: PropTypes.bool,
 
  /** list of key identifiers that will close the list */
  keysCloseList: PropTypes.array,
 
  /** list of key identifiers that will trigger a selection */
  keysSelection: PropTypes.array,
 
  /** Left UI Icon */
  leftIcon: PropTypes.node,
 
  /** Max allowed input value length */
  maxLength: PropTypes.number,
 
  /** Min required input value length */
  minLength: PropTypes.number,
 
  /** if select accept single value or multiple values */
  multiselection: PropTypes.bool,
 
  /** callback to be called when input losses focus */
  onBlur: PropTypes.func,
 
  /** callback to be called with every update of the input value */
  onChange: PropTypes.func,
 
  /** callback to be called when clear icon is clicked */
  onClear: PropTypes.func,
 
  /** callback to be called with every update of the list of tags */
  onChangeTags: PropTypes.func,
 
  /** callback triggered when the user clicks on right icon */
  onClickRightIcon: PropTypes.func,
 
  /** callback triggered when the user press enter when the suggestion is closed */
  onEnter: PropTypes.func,
 
  /** callback triggered when the user focuses on the input */
  onFocus: PropTypes.func,
 
  /** callback triggered when the user selects the suggested item */
  onSelect: PropTypes.func,
 
  /** callback when arrow up/down is clicked → to show/hide list of options */
  onToggle: PropTypes.func,
 
  /** list of values to be displayed on the select */
  options: PropTypes.array,
 
  /** object generated w/ React.createRef method to get a DOM reference of wrapper div */
  refMoleculeAutosuggest: PropTypes.object,
 
  /** object generated w/ React.createRef method to get a DOM reference of internal input */
  refMoleculeAutosuggestInput: PropTypes.object,
 
  /** native required html attribute */
  required: PropTypes.bool,
 
  /** Button prop to be passe down to the input field */
  rightButton: PropTypes.node,
 
  /** Right UI Icon */
  rightIcon: PropTypes.node,
 
  /** size (height) of the list */
  size: PropTypes.oneOf(Object.values(SIZES)),
 
  /** Will set a red/green/orange border if set to 'error' / 'success' / 'alert' */
  state: PropTypes.oneOf(Object.values(AUTOSUGGEST_STATES)),
 
  /** Sets the shape of the input field. It can be 'rounded', 'square' or 'circle' */
  shape: PropTypes.oneOf(Object.values(inputShapes)),
 
  /** native tabIndex html attribute */
  tabIndex: PropTypes.number,
 
  /** list of values displayed as tags */
  tags: PropTypes.array,
 
  /** native input types (text, date, ...), 'sui-password' */
  type: PropTypes.oneOf(Object.values(inputTypes)),
 
  /** value selected */
  value: PropTypes.any
}
 
MoleculeAutosuggest.displayName = 'MoleculeAutosuggest'
 
export {SIZES as MoleculeAutosuggestDropdownListSizes}
export {AUTOSUGGEST_STATES as MoleculeAutosuggestStates}
 
export default MoleculeAutosuggest