import React, { useEffect, useMemo, useState } from 'react' import useTheme from '../use-theme' import withDefaults from '../utils/with-defaults' import { setChildrenProps } from '../utils/collections' import TreeLeaf from './tree-leaf' import Expand from '../shared/expand' import TreeIndents from './tree-indents' import { useTreeContext } from './tree-context' import TreeFolderIcon from './tree-folder-icon' import TreeStatusIcon from './tree-status-icon' import { sortChildren, makeLeafPath, stopPropagation } from './tree-help' interface Props { name: string extra?: string parentPath?: string level?: number className?: string } const defaultProps = { level: 0, className: '', parentPath: '' } type NativeAttrs = Omit, keyof Props> export type TreeFolderProps = Props & typeof defaultProps & NativeAttrs const TreeFolder: React.FC> = ({ name, children, parentPath, level: parentLevel, extra, className, ...props }) => { const theme = useTheme() const { initialExpand, isImperative } = useTreeContext() const [expanded, setExpanded] = useState(initialExpand) // eslint-disable-next-line react-hooks/exhaustive-deps useEffect(() => setExpanded(initialExpand), []) // only set once const currentPath = useMemo(() => makeLeafPath(name, parentPath), []) const nextLeafs = setChildrenProps( children, { parentPath: currentPath, level: parentLevel + 1 }, [TreeFolder, TreeLeaf] ) const { onNodeClick } = useTreeContext() const clickHandler = (event: React.MouseEvent) => { setExpanded(!expanded) if (onNodeClick) { stopPropagation(event) onNodeClick(currentPath) } } const sortedLeafs = isImperative ? nextLeafs : sortChildren(nextLeafs, TreeFolder) return (
{name} {extra && {extra}}
{sortedLeafs}
) } export default withDefaults(TreeFolder, defaultProps)