import React, { useState } from 'react' import classnames from 'classnames' import { globalProps } from '../utilities/globalProps' import { buildAriaProps, buildCss, buildDataProps } from '../utilities/props' import CollapsibleContent from './child_kits/CollapsibleContent' import CollapsibleMain from './child_kits/CollapsibleMain' import CollapsibleContext from './context' import IconSizes from "../pb_icon/_icon" type CollapsibleProps = { children?: JSX.Element | [], aria?: {[key: string]: string}, className?: string, collapsed?: boolean, data?: object, iconColor?: 'default' | 'light' | 'lighter' | 'link' | 'error' | 'success', iconSize?: typeof IconSizes id?: string, padding?: string, } const useCollapsible = (initial = false) => { const [collapsed, setCollapsed] = useState(initial) return [ collapsed, () => setCollapsed((t) => !t), ] } const Collapsible = ({ aria = {}, className, children = [], collapsed = true, data = {}, iconColor = 'default', iconSize, id, padding = 'md', ...props }: CollapsibleProps) => { const [isCollapsed, collapse] = useCollapsible(collapsed) const CollapsibleParent = React.Children.toArray(children) as JSX.Element[] if (CollapsibleParent.length !== 2) { throw new Error('Collapsible requires and to function properly.') } const Main = CollapsibleParent[0] const Content = CollapsibleParent[1] const { children: mainChildren, ...mainProps } = Main.props const { children: contentChildren, ...contentProps } = Content.props const ariaProps = buildAriaProps(aria) const dataProps = buildDataProps(data) const classes = classnames( buildCss('pb_collapsible_kit'), globalProps(props, { padding }), className ) return (
{mainChildren} {contentChildren}
) } Collapsible.Main = CollapsibleMain Collapsible.Content = CollapsibleContent export default Collapsible