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

36.36% Statements 24/66
12.69% Branches 8/63
60% Functions 6/10
38.09% Lines 24/63

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                  1x               7x       7x 7x   7x 7x     7x 6x     7x           7x                                                                                                               7x 9x   9x 9x           18x       7x 9x 9x   9x 4x             5x     7x                               1x   1x                                          
import {Children, cloneElement, isValidElement, useEffect, useRef} 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 tabRefs = useRef([]) // To store refs of each tab item
 
  // Initialize or clear tabRefs based on children length
  useEffect(() => {
    tabRefs.current = tabRefs.current.slice(0, childrenArray.length)
  }, [childrenArray.length])
 
  const focusTab = index => {
    if (tabRefs.current[index]) {
      tabRefs.current[index].focus()
    }
  }
 
  const handleKeyDown = event => {
    const activeTabIndex = childrenArray.findIndex(child => child.props.active)
    let nextTabIndex = activeTabIndex
 
    if (event.key === 'ArrowRight' && !isVerticalOrientation) {
      nextTabIndex = (activeTabIndex + 1) % childrenArray.length
    } else if (event.key === 'ArrowLeft' && !isVerticalOrientation) {
      nextTabIndex = (activeTabIndex - 1 + childrenArray.length) % childrenArray.length
    } else if (event.key === 'ArrowDown' && isVerticalOrientation) {
      nextTabIndex = (activeTabIndex + 1) % childrenArray.length
    } else if (event.key === 'ArrowUp' && isVerticalOrientation) {
      nextTabIndex = (activeTabIndex - 1 + childrenArray.length) % childrenArray.length
    } else if (event.key === 'Home') {
      nextTabIndex = 0
    } else if (event.key === 'End') {
      nextTabIndex = childrenArray.length - 1
    }
 
    if (nextTabIndex !== activeTabIndex) {
      event.preventDefault()
      const nextTab = childrenArray[nextTabIndex]
      if (nextTab && !nextTab.props.disabled) {
        onChange(event, {numTab: nextTabIndex + 1})
        focusTab(nextTabIndex)
      } else {
        // If the next tab is disabled, try to find the next available tab in that direction
        let potentialNextTabIndex = nextTabIndex
        const increment = event.key === 'ArrowRight' || event.key === 'ArrowDown' || event.key === 'End' ? 1 : -1
        while (childrenArray[potentialNextTabIndex] && childrenArray[potentialNextTabIndex].props.disabled) {
          potentialNextTabIndex = (potentialNextTabIndex + increment + childrenArray.length) % childrenArray.length
          // Avoid infinite loop if all other tabs are disabled
          if (potentialNextTabIndex === activeTabIndex) break
        }
        if (childrenArray[potentialNextTabIndex] && !childrenArray[potentialNextTabIndex].props.disabled) {
          onChange(event, {numTab: potentialNextTabIndex + 1})
          focusTab(potentialNextTabIndex)
        }
      }
    } else if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault() // Prevent default action (e.g., scrolling for space)
      const focusedTabElement = event.target
      const focusedTabIndex = tabRefs.current.findIndex(ref => ref === focusedTabElement)
 
      if (focusedTabIndex !== -1) {
        const targetChild = childrenArray[focusedTabIndex]
        if (targetChild && !targetChild.props.disabled) {
          // Only call onChange if the focused tab is not already active
          if (focusedTabIndex !== activeTabIndex) {
            onChange(event, {numTab: focusedTabIndex + 1})
            // Focus is already on the tab due to Tab key navigation
          }
        }
      }
    }
  }
 
  const extendedChildren = childrenArray
    .filter(child => isValidElement(child))
    .map((child, index) => {
      const numTab = index + 1
      return cloneElement(child, {
        autoScrollIntoView,
        isIntersecting,
        numTab,
        id,
        onChange,
        ref: el => (tabRefs.current[index] = el) // Assign ref to each MoleculeTab
      })
    })
 
  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}
        onKeyDown={handleKeyDown} // Add keydown handler
      >
        {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