import React , { useState , useMemo } from 'react' ; import { IProps , HTMLDivProps } from '@uiw/utils' ; import Panel from './Panel' ; import './style/index.less' ; export interface CollapseProps extends IProps , Omit < HTMLDivProps , 'onChange' > { accordion ? : boolean ; activeKey ? : string | string [ ] ; bordered ? : boolean ; showArrow ? : boolean ; onChange ? : ( activeKey : string [ ] ) => void ; } export interface CollapseState { activeKey : string [ ] ; } function toArray ( activeKey ) { let currentActiveKey = activeKey ; if ( ! Array . isArray ( currentActiveKey ) ) { currentActiveKey = currentActiveKey ? [ currentActiveKey ] : [ ] ; } return currentActiveKey ; } function InternalCollapse ( props , ref ) { const { prefixCls = 'w-collapse' , className , children , accordion = false , bordered , showArrow = true , activeKey : propsActiveKey , onChange , ... resetProps } = props ; const [ activeKey , setActiveKey ] = useState ( toArray ( propsActiveKey ) ) ; const cls = [ prefixCls , className , bordered ? 'w-noborder' : null ] . filter ( Boolean ) . join ( ' ' ) . trim ( ) ; function onItemClick ( key ) { let keys = activeKey ; if ( accordion ) { keys = keys [ 0 ] === key ? [ ] : [ key ] ; } else { keys = [ ... keys ] ; const index = keys . indexOf ( key ) ; const isActive = index > - 1 ; if ( isActive ) { keys . splice ( index , 1 ) ; } else { keys . push ( key ) ; } } setActiveKey ( keys ) ; } useMemo ( ( ) => { if ( propsActiveKey !== activeKey ) { setActiveKey ( toArray ( propsActiveKey ) ) ; } } , [ propsActiveKey ] ) ; useMemo ( ( ) => { if ( propsActiveKey !== activeKey ) { onChange && onChange ( activeKey ) ; } } , [ activeKey , propsActiveKey ] ) ; return ( < div className = { cls } { ... resetProps } ref = { ref } > { React . Children . map ( children , ( child , index ) => { const key = child . key || String ( index ) ; const { disabled } = child . props ; let isActive = false ; if ( accordion ) { isActive = activeKey [ 0 ] === key ; } else { isActive = activeKey . indexOf ( key ) > - 1 ; } const childProps = { prefixCls , isActive , disabled , showArrow , onItemClick : disabled ? ( ) => { } : ( ) => onItemClick ( key ) , ... child . props , } ; return React . cloneElement ( child , childProps ) ; } ) } < /div>); } const Collapse = React . forwardRef < HTMLDivElement , CollapseProps > ( InternalCollapse ) ; type Collapse = typeof Collapse & { Panel : typeof Panel ; } ; ( Collapse as Collapse ) . Panel = Panel ; export default Collapse as Collapse ;