All files / ResponsiveButtonGroup ResponsiveButtonGroup.js

13.51% Statements 5/37
0% Branches 0/35
0% Functions 0/13
13.88% Lines 5/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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171                                27x                     27x 27x                               27x                                                                                                                                                                                                                                                     27x      
import { cloneElement, isValidElement, useCallback, useMemo } from 'react';
 
import PropTypes from 'prop-types';
import classnames from 'classnames';
 
import {
  Button,
  Dropdown,
  DropdownMenu,
  Icon
} from '@folio/stripes/components';
 
import css from '../../../styles/ResponsiveButtonGroup.css';
 
import useResponsiveButtonGroupSizing from './useResponsiveButtonGroupSizing';
 
const propTypes = {
  children: PropTypes.node,
  className: PropTypes.string,
  dropdownTriggerProps: PropTypes.object,
  fullWidth: PropTypes.bool,
  id: PropTypes.string,
  marginBottom0: PropTypes.bool,
  selectedIndex: PropTypes.number,
  tagName: PropTypes.string,
};
 
const SIZE_OF_DOWN_ARROW_BUTTON = 46;
const calculateCumulativeThreshold = (arrayOfNumbers, maximum, index = 0, value = 0) => {
  // If all the numbers fit, return the last index
  if (arrayOfNumbers.reduce((partialSum, a) => partialSum + a, 0) <= maximum) {
    return arrayOfNumbers?.length - 1;
  }
 
  // Else we'll need a down arrow button, so include that in calculations
  const nextValue = value + arrayOfNumbers[index];
  if (nextValue + SIZE_OF_DOWN_ARROW_BUTTON <= maximum && (index + 1 < arrayOfNumbers?.length)) {
    return calculateCumulativeThreshold(arrayOfNumbers, maximum, index + 1, nextValue);
  }
 
  return index - 1;
};
 
 
const ResponsiveButtonGroup = (props) => {
  const {
    children: childButtons, // These MUST consist only of Button components
    className,
    dropdownTriggerProps = {},
    fullWidth = false, // Only bother with this when buttonGroupWidth < ContainerWidth
    id,
    marginBottom0, // Will ONLL control the margin of the dropdown button
    selectedIndex,
    tagName: Tag = 'div',
    ...rest
  } = props;
 
  const sanitizedButtons = useMemo(() => {
    const arr = Array.isArray(childButtons) ? childButtons : [childButtons];
    return arr.filter(isValidElement);
  }, [childButtons]);
 
  const {
    buttons,
    cachedSizeArray,
    containerRef,
    containerWidth,
    ready,
  } = useResponsiveButtonGroupSizing({
    buttons: sanitizedButtons,
    id
  });
 
  const buttonThreshold = calculateCumulativeThreshold(cachedSizeArray, containerWidth);
 
  const renderActionMenuToggle = useCallback(({ displayButtons, onToggle, triggerRef, keyHandler, open, ariaProps, getTriggerProps }) => (
    <Button
      ref={triggerRef}
      aria-label="menu"
      buttonClass={
        classnames(
          css.width100,
          { [`${css.dropdownButtonClass}`]: (displayButtons?.length ?? 0) > 0 },
          { [`${css.marginBottom}`]: !marginBottom0 },
          { [`${css.marginBottom0}`]: marginBottom0 }
        )
      }
      buttonStyle={selectedIndex > buttonThreshold ? 'primary' : 'default'}
      onClick={onToggle}
      onKeyDown={keyHandler}
      type="button"
      {...getTriggerProps()}
      {...ariaProps}
      {...dropdownTriggerProps}
    >
      <Icon icon={open ? 'triangle-up' : 'triangle-down'} iconPosition="end" />
    </Button>
  ), [buttonThreshold, dropdownTriggerProps, marginBottom0, selectedIndex]);
 
  const displayButtons = useMemo(() => (
    buttons?.slice(0, buttonThreshold + 1)?.map((button, index) => {
      if (index === selectedIndex && !button?.buttonStyle) {
        return cloneElement(button, { buttonStyle: 'primary' });
      }
 
      return button;
    })
  ), [buttonThreshold, buttons, selectedIndex]);
 
  const dropdownButtons = useMemo(() => (
    [...buttons
      .slice(buttonThreshold + 1, buttons?.length)
      ?.map(button => {
        return cloneElement(button, { buttonStyle: 'dropdownItem' });
      })
    ]
  ), [buttonThreshold, buttons]);
 
  // eslint-disable-next-line react/prop-types
  const renderActionMenuContent = useCallback(() => (
    <DropdownMenu>
      {[...dropdownButtons]}
    </DropdownMenu>
  ), [dropdownButtons]);
 
  const buttonsSlice = useMemo(() => (
    [
      ...displayButtons,
      <Dropdown
        key="responsiveButtonGroup-dropdown-toggle"
        className={css.dropdownClass}
        renderMenu={renderActionMenuContent}
        renderTrigger={(triggerProps) => renderActionMenuToggle({ displayButtons, ...triggerProps })}
      />
    ]
  ), [displayButtons, renderActionMenuContent, renderActionMenuToggle]);
 
  return (
    <>
      <div ref={containerRef} className="width: 100%;" />
      <Tag
        className={
          classnames(
            { [`${css.hidden}`]: !ready },
            css.buttonGroup,
            { [`${css.fullWidth}`]: ready && fullWidth },
            className
          )
        }
        style={fullWidth ? { width: `${containerWidth}px` } : {}}
        {...rest}
      >
        {!ready || buttonThreshold === cachedSizeArray?.length - 1 ?
          buttons?.map((button, index) => {
            if (index === selectedIndex && !button?.buttonStyle) {
              return cloneElement(button, { buttonStyle: 'primary' });
            }
 
            return button;
          }) :
          buttonsSlice
        }
      </Tag>
    </>
  );
};
 
ResponsiveButtonGroup.propTypes = propTypes;
 
export default ResponsiveButtonGroup;