UNPKG

@equinor/eds-core-react

Version:

The React implementation of the Equinor Design System

60 lines (57 loc) 2.06 kB
import { forwardRef, useState, useEffect, Children, isValidElement, cloneElement } from 'react'; import { jsx } from 'react/jsx-runtime'; import { Tooltip } from '../../Tooltip/Tooltip.js'; import { ButtonGroup } from '../ButtonGroup/ButtonGroup.js'; const ToggleButton = /*#__PURE__*/forwardRef(function ToggleButton({ children, multiple, selectedIndexes, onChange, ...props }, ref) { const [pickedIndexes, setPickedIndexes] = useState(selectedIndexes || []); useEffect(() => { if (Array.isArray(selectedIndexes)) { setPickedIndexes(selectedIndexes); } }, [selectedIndexes]); function updateProps(child, isSelected, index) { const childElement = child; if (/*#__PURE__*/isValidElement(child)) { const buttonProps = { 'aria-pressed': isSelected ? true : undefined, variant: isSelected ? 'contained' : 'outlined', onClick: e => { childElement.props?.onClick?.(e); let updatedSelection = [index]; if (multiple) { updatedSelection = pickedIndexes.includes(index) ? pickedIndexes.filter(i => i !== index) : [...pickedIndexes, index]; } setPickedIndexes(updatedSelection); if (onChange) { onChange(updatedSelection); } } }; return /*#__PURE__*/cloneElement(child, buttonProps); } } const updatedChildren = Children.map(children, (child, index) => { const isSelected = pickedIndexes.includes(index); const childElement = child; if (/*#__PURE__*/isValidElement(child) && child.type === Tooltip) { const updatedGrandChildren = Children.map(childElement.props.children, grandChild => { return updateProps(grandChild, isSelected, index); }); return /*#__PURE__*/cloneElement(childElement, null, updatedGrandChildren[0]); } else { return updateProps(childElement, isSelected, index); } }); return /*#__PURE__*/jsx(ButtonGroup, { ref: ref, ...props, children: updatedChildren }); }); export { ToggleButton };