diff --git a/src/components/json-tree-node/index.tsx b/src/components/json-tree-node/index.tsx index 2ab982d..d076cdf 100644 --- a/src/components/json-tree-node/index.tsx +++ b/src/components/json-tree-node/index.tsx @@ -1,4 +1,4 @@ -import { useMemo } from "react" +import { useMemo, useState } from "react" import jp, { PathComponent } from "jsonpath" import _ from "lodash" @@ -6,11 +6,13 @@ export interface JsonTreeNodeProps { data: unknown path: PathComponent[] matchedPaths: string[] + defaultExpanded?: boolean } -export default function JsonTreeNode({ data, path, matchedPaths }: JsonTreeNodeProps) { +export default function JsonTreeNode({ data, path, matchedPaths, defaultExpanded = true }: JsonTreeNodeProps) { const currentPathString = useMemo(() => jp.stringify(path), [path]) const isMatched = matchedPaths.includes(currentPathString) + const [expanded, setExpanded] = useState(defaultExpanded) const highlightClass = isMatched ? "bg-yellow-200 ring-2 ring-yellow-400 rounded-sm" : "" @@ -20,19 +22,31 @@ export default function JsonTreeNode({ data, path, matchedPaths }: JsonTreeNodeP return (
- {isArray ? "[" : "{"} - {entries.map(([key, value], index) => { - const nextPath = [...path, isArray ? Number(key) : key] + setExpanded(!expanded)} + > + {expanded ? "▼" : "▶"} + {isArray ? "[" : "{"} + {!expanded && …{entries.length} items} + {!expanded && {isArray ? "]" : "}"}} + + {expanded && ( + <> + {entries.map(([key, value], index) => { + const nextPath = [...path, isArray ? Number(key) : key] - return ( -
- {!isArray && "{key}": } - - {index < entries.length - 1 && ,} -
- ) - })} - {isArray ? "]" : "}"} + return ( +
+ {!isArray && "{key}": } + + {index < entries.length - 1 && ,} +
+ ) + })} + {isArray ? "]" : "}"} + + )}
) }