All files / molecule/dropdownList/src index.js

36.36% Statements 16/44
18.18% Branches 8/44
33.33% Functions 3/9
41.66% Lines 15/36

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                                      1x                                 11x 11x   11x 11x   11x                   11x               11x                                                         11x 11x     11x   10x         5x                 1x   1x                                                                                
import {Children, forwardRef, useEffect, useRef, useState} from 'react'
 
import cx from 'classnames'
import PropTypes from 'prop-types'
 
import useDebounce from '@s-ui/react-hooks/lib/useDebounce'
import useMergeRefs from '@s-ui/react-hooks/lib/useMergeRefs'
 
import {
  BASE_CLASS,
  CLASS_HIDDEN,
  DEBOUNCE_TIME,
  DESIGNS,
  moleculeDropdownListSelectHandler,
  POSITIONS,
  SIZES
} from './config.js'
import ExtendedChildren from './ExtendedChildren.js'
 
const MoleculeDropdownList = forwardRef(
  (
    {
      children,
      onSelect,
      position = POSITIONS.BOTTOM,
      alwaysRender = true,
      design = DESIGNS.SOLID,
      size = SIZES.SMALL,
      value,
      visible,
      onKeyDown,
      'aria-label': ariaLabel,
      ...props
    },
    forwardedRef
  ) => {
    const refDropdownList = useRef()
    const ref = useMergeRefs(refDropdownList, forwardedRef)
 
    const [typedWord, setTypedWord] = useState('')
    const debouncedTypedWord = useDebounce(typedWord, DEBOUNCE_TIME)
 
    const classNames = cx(
      BASE_CLASS,
      `${BASE_CLASS}--position-${position}`,
      `${BASE_CLASS}--design-${design}`,
      `${BASE_CLASS}--size-${size}`,
      {
        [CLASS_HIDDEN]: !visible
      }
    )
 
    const getFocusedOptionIndex = options => {
      const currentElementFocused = document.activeElement
      return Array.from(options).reduce((focusedOptionIndex, option, index) => {
        if (option === currentElementFocused) focusedOptionIndex = index
        return focusedOptionIndex
      }, 0)
    }
 
    const handleKeyDown = event => {
      const {key} = event
      const {
        current: {children: options}
      } = refDropdownList
      const numOptions = options.length
      const index = getFocusedOptionIndex(options)
      if (key === 'ArrowDown' || key === 'ArrowUp') {
        if (index >= 0 || index <= numOptions) {
          if (position === POSITIONS.TOP) {
            if (key === 'ArrowDown' && index > 0) options[index - 1].focus()
            if (key === 'ArrowUp' && index < numOptions - 1) options[index + 1].focus()
          } else {
            if (key === 'ArrowDown' && index < numOptions - 1) options[index + 1].focus()
            if (key === 'ArrowUp' && index > 0) options[index - 1].focus()
          }
        }
      } else {
        setTypedWord(value => value + key.toLowerCase())
        const word = typedWord + key.toLowerCase()
        const optionToFocusOn =
          Array.from(options).find((option, i) => i >= index && option.innerText.toLowerCase().indexOf(word) === 0) ||
          Array.from(options).find(option => option.innerText.toLowerCase().indexOf(word) === 0)
        optionToFocusOn && optionToFocusOn.focus()
      }
      typeof onKeyDown === 'function' && onKeyDown(event)
    }
 
    // When DEBOUNCE_TIME reset typed word
    useEffect(() => {
      setTypedWord('')
    }, [debouncedTypedWord])
 
    if (!visible && !alwaysRender) return null
 
    return (
      <ul ref={ref} tabIndex={0} onKeyDown={handleKeyDown} className={classNames} role="listbox" aria-label={ariaLabel}>
        {Children.toArray(children)
          .filter(Boolean)
          .map((child, index) => (
            <ExtendedChildren key={index} value={value} onSelect={onSelect} {...props}>
              {child}
            </ExtendedChildren>
          ))}
      </ul>
    )
  }
)
 
MoleculeDropdownList.displayName = 'MoleculeDropdownList'
 
MoleculeDropdownList.propTypes = {
  /** No matter if is visible or invisible, render always the content */
  alwaysRender: PropTypes.bool,
 
  /** aria-label for accessibility */
  'aria-label': PropTypes.string,
 
  /** Content to be included in the list (MoleculeDropdownOption) */
  children: PropTypes.node,
 
  /** callback on select option */
  onSelect: PropTypes.func,
 
  /** checkbox contained in all DropdownOption **/
  checkbox: PropTypes.bool,
 
  /** design (flat|solid) of the list */
  design: PropTypes.oneOf(Object.values(DESIGNS)),
 
  /** size (height) of the list */
  size: PropTypes.oneOf(Object.values(SIZES)),
 
  /** position of the list (top, bottom) default bottom */
  position: PropTypes.oneOf(Object.values(POSITIONS)),
 
  /** selected value */
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
 
  /** Visible or not */
  visible: PropTypes.bool,
 
  /** Keydown handler callback **/
  onKeyDown: PropTypes.func
}
 
export default MoleculeDropdownList
export {DESIGNS as moleculeDropdownListDesigns}
export {SIZES as moleculeDropdownListSizes}
export {POSITIONS as moleculeDropdownListPositions}
export {moleculeDropdownListSelectHandler}