import React, { useMemo } from 'react' import withDefaults from '../utils/with-defaults' import useTheme from '../use-theme' import { CollapseContext, CollapseConfig } from './collapse-context' import useCurrentState from '../utils/use-current-state' import { setChildrenIndex } from '../utils/collections' import Collapse from './collapse' interface Props { accordion?: boolean className?: string } const defaultProps = { accordion: true, className: '' } type NativeAttrs = Omit, keyof Props> export type CollapseGroupProps = Props & typeof defaultProps & NativeAttrs const CollapseGroup: React.FC> = ({ children, accordion, className, ...props }) => { const theme = useTheme() const [state, setState, stateRef] = useCurrentState>([]) const updateValues = (currentIndex?: number, nextState?: boolean) => { const safeIndex = currentIndex || 0 const hasChild = stateRef.current.find((val) => val === currentIndex) if (accordion) { if (nextState) return setState([safeIndex]) return setState([]) } if (nextState) { // In a few cases, the user will set Collapse Component state manually. // If the user incorrectly set the state, Group component should ignore it. /* istanbul ignore if */ if (hasChild) return return setState([...stateRef.current, safeIndex]) } setState(stateRef.current.filter((item) => item !== currentIndex)) } const initialValue = useMemo( () => ({ values: state, updateValues }), [state.join(',')] ) const hasIndexChildren = useMemo(() => setChildrenIndex(children, [Collapse]), [children]) return (
{hasIndexChildren}
) } export default withDefaults(CollapseGroup, defaultProps)