All files / atom/tag/src/Actionable Container.js

53.84% Statements 7/13
47.61% Branches 10/21
50% Functions 1/2
58.33% Lines 7/12

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                      1x                                     4x 4x 4x 4x               4x                               1x                                
import {forwardRef} from 'react'
 
import PropTypes from 'prop-types'
 
import useControlledState from '@s-ui/react-hooks/lib/useControlledState'
 
import {LINK_TYPES, onHandler} from '../constants.js'
 
/**
 * Component treated as an anchor when href is defined
 */
const ActionableTagContainer = forwardRef(
  (
    {
      link: Link,
      href,
      target,
      rel,
      readOnly,
      disabled,
      children,
      pressed,
      defaultPressed,
      onClick,
      label,
      value,
      ...props
    },
    forwardedRef
  ) => {
    const isButton = href === undefined
    const Component = isButton ? 'button' : Link
    const [innerPressed, setInnerPressed] = useControlledState(pressed, defaultPressed)
    const onClickHandler = (event, {...args}) => {
      if (disabled || readOnly) return
      const hasPressed = innerPressed !== undefined
      onClick && onClick(event, {...args, ...(hasPressed && {label, value, pressed: !!innerPressed})})
      if (hasPressed) {
        setInnerPressed(!innerPressed)
      }
    }
    return (
      <Component
        ref={forwardedRef}
        {...(href ? {href, target, rel} : {})}
        {...(disabled && {disabled})}
        {...(readOnly && !disabled && {'data-read-only': readOnly})}
        {...(innerPressed !== undefined && {'aria-pressed': innerPressed})}
        onClick={onHandler({disabled, readOnly}, onClickHandler)}
        {...props}
      >
        {children}
      </Component>
    )
  }
)
 
ActionableTagContainer.propTypes = {
  link: PropTypes.node,
  href: PropTypes.string,
  target: PropTypes.oneOf(['_self', '_blank', '_parent', '_top']),
  rel: PropTypes.arrayOf(PropTypes.oneOf(Object.values(LINK_TYPES))),
  readOnly: PropTypes.bool,
  disabled: PropTypes.bool,
  children: PropTypes.node.isRequired,
  pressed: PropTypes.bool,
  defaultPressed: PropTypes.bool,
  onClick: PropTypes.func,
  label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]).isRequired,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
}
 
export default ActionableTagContainer