|
| 1 | +import * as React from "react" |
| 2 | + |
| 3 | +import { css } from "../../css/css.js" |
| 4 | +import { Collapse } from "../Collapse.js" |
| 5 | +import { useTreeContext } from "./TreeRoot.js" |
| 6 | + |
| 7 | +const NodeCss = css({ |
| 8 | + margin: 0, |
| 9 | + padding: 0, |
| 10 | + cursor: "pointer", |
| 11 | + userSelect: "none", |
| 12 | +}) |
| 13 | + |
| 14 | +const NodeItemCss = css({ |
| 15 | + "&:hover": { |
| 16 | + background: "AliceBlue", |
| 17 | + }, |
| 18 | +}) |
| 19 | + |
| 20 | +const NodeContainerCss = css({ |
| 21 | + margin: 0, |
| 22 | + padding: 0, |
| 23 | + listStyle: "none", |
| 24 | +}) |
| 25 | + |
| 26 | +export interface TreeNodeProps { |
| 27 | + item: React.ReactNode |
| 28 | +} |
| 29 | + |
| 30 | +interface InternalTreeProps extends TreeNodeProps { |
| 31 | + __depth: number |
| 32 | +} |
| 33 | + |
| 34 | +export function TreeNode({ children, ...props }: React.PropsWithChildren<TreeNodeProps>) { |
| 35 | + const [open, setOpen] = React.useState(false) |
| 36 | + |
| 37 | + const { item, __depth = 0 } = props as InternalTreeProps |
| 38 | + |
| 39 | + const { indentSize } = useTreeContext() |
| 40 | + |
| 41 | + // Add the internal depth property to the elements. We either expect an array or a single |
| 42 | + // item. Note the user should be using TreeNode component, if they've provided other types |
| 43 | + // of React components, we don't do anything, but will render them as normal. |
| 44 | + let childElements |
| 45 | + if (Array.isArray(children)) { |
| 46 | + childElements = children.map((child) => { |
| 47 | + if ((child as JSX.Element)?.type?.name === "TreeNode") { |
| 48 | + return React.cloneElement(child as JSX.Element, { __depth: __depth + 1 }) |
| 49 | + } |
| 50 | + return child |
| 51 | + }) |
| 52 | + } else { |
| 53 | + if ((children as JSX.Element)?.type?.name === "TreeNode") { |
| 54 | + childElements = React.cloneElement(children as JSX.Element, { __depth: __depth + 1 }) |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + const indentValue = |
| 59 | + typeof indentSize === "number" ? indentSize * __depth : `calc(${indentSize} * ${__depth})` |
| 60 | + |
| 61 | + return ( |
| 62 | + <li className={NodeCss()}> |
| 63 | + <div |
| 64 | + onClick={() => setOpen((prev) => !prev)} |
| 65 | + className={NodeItemCss({ css: { paddingLeft: __depth && indentValue } })} |
| 66 | + > |
| 67 | + {item} |
| 68 | + </div> |
| 69 | + {childElements && ( |
| 70 | + <Collapse as="ul" open={open} className={NodeContainerCss()}> |
| 71 | + {childElements} |
| 72 | + </Collapse> |
| 73 | + )} |
| 74 | + </li> |
| 75 | + ) |
| 76 | +} |
0 commit comments