All files / molecule/tabs/src/components MoleculeTabs.js

100% Statements 18/18
80% Branches 8/10
100% Functions 4/4
100% Lines 18/18

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                  1x               7x       7x 7x   7x   7x 9x   9x 9x                 7x 9x 9x   9x 4x             5x     7x                             1x   1x                                          
import {Children, cloneElement, isValidElement} from 'react'
 
import cx from 'classnames'
import PropTypes from 'prop-types'
 
import useOnScreen from '@s-ui/react-hooks/lib/useOnScreen'
 
import {BASE_CLASS, CLASS_CONTENT, CLASS_SCROLLER, TYPES, VARIANTS} from '../config.js'
 
const MoleculeTabs = ({
  autoScrollIntoView = true,
  children,
  id = 'molecule-tab-content',
  onChange,
  type = TYPES.HORIZONTAL,
  variant = VARIANTS.CLASSIC
}) => {
  const className = cx(BASE_CLASS, {
    [`${BASE_CLASS}--${variant}`]: variant,
    [`${BASE_CLASS}--${type}`]: type
  })
  const childrenArray = Children.toArray(children)
  const isVerticalOrientation = type === TYPES.VERTICAL
 
  const [isIntersecting, outerRef] = useOnScreen()
 
  const extendedChildren = childrenArray
    .filter(child => isValidElement(child))
    .map((child, index) => {
      const numTab = index + 1
      return cloneElement(child, {
        autoScrollIntoView,
        isIntersecting,
        numTab,
        id,
        onChange
      })
    })
 
  const activeTabContent = childrenArray.reduce((activeContent, child) => {
    Eif (child) {
      const {children: childrenChild, active, numTab} = child.props
 
      if (active) {
        return (
          <div className={CLASS_CONTENT} id={`${id}-${numTab}`} role="tabpanel">
            {childrenChild}
          </div>
        )
      }
    }
    return activeContent
  }, null)
 
  return (
    <div className={className}>
      <ul
        ref={outerRef}
        className={CLASS_SCROLLER}
        role="tablist"
        aria-orientation={isVerticalOrientation ? TYPES.VERTICAL : TYPES.HORIZONTAL}
      >
        {extendedChildren}
      </ul>
      {activeTabContent}
    </div>
  )
}
 
MoleculeTabs.displayName = 'MoleculeTabs'
 
MoleculeTabs.propTypes = {
  /** Enable scroll into view funcionality */
  autoScrollIntoView: PropTypes.bool,
 
  /** children */
  children: PropTypes.any,
 
  /** id used to make tabs unique */
  id: PropTypes.string,
 
  /** onChange */
  onChange: PropTypes.func,
 
  /** variant */
  variant: PropTypes.oneOf(Object.values(VARIANTS)),
 
  /** type */
  type: PropTypes.oneOf(Object.values(TYPES))
}
 
export default MoleculeTabs