1"use client";
2
3import { ChevronRight, File, Folder, FolderOpen } from "lucide-react";
4import { AnimatePresence, motion } from "motion/react";
5import {
6 type ComponentProps,
7 createContext,
8 type HTMLAttributes,
9 type ReactNode,
10 useCallback,
11 useContext,
12 useId,
13 useState,
14} from "react";
15import { cn } from "@/lib/utils";
16
17type TreeContextType = {
18 expandedIds: Set<string>;
19 selectedIds: string[];
20 toggleExpanded: (nodeId: string) => void;
21 handleSelection: (nodeId: string, ctrlKey: boolean) => void;
22 showLines?: boolean;
23 showIcons?: boolean;
24 selectable?: boolean;
25 multiSelect?: boolean;
26 indent?: number;
27 animateExpand?: boolean;
28};
29
30const TreeContext = createContext<TreeContextType | undefined>(undefined);
31
32const useTree = () => {
33 const context = useContext(TreeContext);
34 if (!context) {
35 throw new Error("Tree components must be used within a TreeProvider");
36 }
37 return context;
38};
39
40type TreeNodeContextType = {
41 nodeId: string;
42 level: number;
43 isLast: boolean;
44 parentPath: boolean[];
45};
46
47const TreeNodeContext = createContext<TreeNodeContextType | undefined>(
48 undefined
49);
50
51const useTreeNode = () => {
52 const context = useContext(TreeNodeContext);
53 if (!context) {
54 throw new Error("TreeNode components must be used within a TreeNode");
55 }
56 return context;
57};
58
59export type TreeProviderProps = {
60 children: ReactNode;
61 defaultExpandedIds?: string[];
62 showLines?: boolean;
63 showIcons?: boolean;
64 selectable?: boolean;
65 multiSelect?: boolean;
66 selectedIds?: string[];
67 onSelectionChange?: (selectedIds: string[]) => void;
68 indent?: number;
69 animateExpand?: boolean;
70 className?: string;
71};
72
73export const TreeProvider = ({
74 children,
75 defaultExpandedIds = [],
76 showLines = true,
77 showIcons = true,
78 selectable = true,
79 multiSelect = false,
80 selectedIds,
81 onSelectionChange,
82 indent = 20,
83 animateExpand = true,
84 className,
85}: TreeProviderProps) => {
86 const [expandedIds, setExpandedIds] = useState<Set<string>>(
87 new Set(defaultExpandedIds)
88 );
89 const [internalSelectedIds, setInternalSelectedIds] = useState<string[]>(
90 selectedIds ?? []
91 );
92
93 const isControlled =
94 selectedIds !== undefined && onSelectionChange !== undefined;
95 const currentSelectedIds = isControlled ? selectedIds : internalSelectedIds;
96
97 const toggleExpanded = useCallback((nodeId: string) => {
98 setExpandedIds((prev) => {
99 const newSet = new Set(prev);
100 if (newSet.has(nodeId)) {
101 newSet.delete(nodeId);
102 } else {
103 newSet.add(nodeId);
104 }
105 return newSet;
106 });
107 }, []);
108
109 const handleSelection = useCallback(
110 (nodeId: string, ctrlKey = false) => {
111 if (!selectable) {
112 return;
113 }
114
115 let newSelection: string[];
116
117 if (multiSelect && ctrlKey) {
118 newSelection = currentSelectedIds.includes(nodeId)
119 ? currentSelectedIds.filter((id) => id !== nodeId)
120 : [...currentSelectedIds, nodeId];
121 } else {
122 newSelection = currentSelectedIds.includes(nodeId) ? [] : [nodeId];
123 }
124
125 if (isControlled) {
126 onSelectionChange?.(newSelection);
127 } else {
128 setInternalSelectedIds(newSelection);
129 }
130 },
131 [
132 selectable,
133 multiSelect,
134 currentSelectedIds,
135 isControlled,
136 onSelectionChange,
137 ]
138 );
139
140 return (
141 <TreeContext.Provider
142 value={{
143 expandedIds,
144 selectedIds: currentSelectedIds,
145 toggleExpanded,
146 handleSelection,
147 showLines,
148 showIcons,
149 selectable,
150 multiSelect,
151 indent,
152 animateExpand,
153 }}
154 >
155 <motion.div
156 animate={{ opacity: 1, y: 0 }}
157 className={cn("w-full", className)}
158 initial={{ opacity: 0, y: 10 }}
159 transition={{ duration: 0.3, ease: "easeOut" }}
160 >
161 {children}
162 </motion.div>
163 </TreeContext.Provider>
164 );
165};
166
167export type TreeViewProps = HTMLAttributes<HTMLDivElement>;
168
169export const TreeView = ({ className, children, ...props }: TreeViewProps) => (
170 <div className={cn("p-2", className)} {...props}>
171 {children}
172 </div>
173);
174
175export type TreeNodeProps = HTMLAttributes<HTMLDivElement> & {
176 nodeId?: string;
177 level?: number;
178 isLast?: boolean;
179 parentPath?: boolean[];
180 children?: ReactNode;
181};
182
183export const TreeNode = ({
184 nodeId: providedNodeId,
185 level = 0,
186 isLast = false,
187 parentPath = [],
188 children,
189 className,
190 onClick,
191 ...props
192}: TreeNodeProps) => {
193 const generatedId = useId();
194 const nodeId = providedNodeId ?? generatedId;
195
196 // Build the parent path - mark positions where the parent was the last child
197 const currentPath = level === 0 ? [] : [...parentPath];
198 if (level > 0 && parentPath.length < level - 1) {
199 // Fill in missing levels with false (not last)
200 while (currentPath.length < level - 1) {
201 currentPath.push(false);
202 }
203 }
204 if (level > 0) {
205 currentPath[level - 1] = isLast;
206 }
207
208 return (
209 <TreeNodeContext.Provider
210 value={{
211 nodeId,
212 level,
213 isLast,
214 parentPath: currentPath,
215 }}
216 >
217 <div className={cn("select-none", className)} {...props}>
218 {children}
219 </div>
220 </TreeNodeContext.Provider>
221 );
222};
223
224export type TreeNodeTriggerProps = ComponentProps<typeof motion.div>;
225
226export const TreeNodeTrigger = ({
227 children,
228 className,
229 onClick,
230 ...props
231}: TreeNodeTriggerProps) => {
232 const { selectedIds, toggleExpanded, handleSelection, indent } = useTree();
233 const { nodeId, level } = useTreeNode();
234 const isSelected = selectedIds.includes(nodeId);
235
236 return (
237 <motion.div
238 className={cn(
239 "group relative mx-1 flex cursor-pointer items-center rounded-md px-3 py-2 transition-all duration-200",
240 "hover:bg-accent/50",
241 isSelected && "bg-accent/80",
242 className
243 )}
244 onClick={(e) => {
245 toggleExpanded(nodeId);
246 handleSelection(nodeId, e.ctrlKey || e.metaKey);
247 onClick?.(e);
248 }}
249 style={{ paddingLeft: level * (indent ?? 0) + 8 }}
250 whileTap={{ scale: 0.98, transition: { duration: 0.1 } }}
251 {...props}
252 >
253 <TreeLines />
254 {children as ReactNode}
255 </motion.div>
256 );
257};
258
259export const TreeLines = () => {
260 const { showLines, indent } = useTree();
261 const { level, isLast, parentPath } = useTreeNode();
262
263 if (!showLines || level === 0) {
264 return null;
265 }
266
267 return (
268 <div className="pointer-events-none absolute top-0 bottom-0 left-0">
269 {/* Render vertical lines for all parent levels */}
270 {Array.from({ length: level }, (_, index) => {
271 const shouldHideLine = parentPath[index] === true;
272 if (shouldHideLine && index === level - 1) {
273 return null;
274 }
275
276 return (
277 <div
278 className="absolute top-0 bottom-0 border-border/40 border-l"
279 key={index.toString()}
280 style={{
281 left: index * (indent ?? 0) + 12,
282 display: shouldHideLine ? "none" : "block",
283 }}
284 />
285 );
286 })}
287
288 {/* Horizontal connector line */}
289 <div
290 className="absolute top-1/2 border-border/40 border-t"
291 style={{
292 left: (level - 1) * (indent ?? 0) + 12,
293 width: (indent ?? 0) - 4,
294 transform: "translateY(-1px)",
295 }}
296 />
297
298 {/* Vertical line to midpoint for last items */}
299 {isLast && (
300 <div
301 className="absolute top-0 border-border/40 border-l"
302 style={{
303 left: (level - 1) * (indent ?? 0) + 12,
304 height: "50%",
305 }}
306 />
307 )}
308 </div>
309 );
310};
311
312export type TreeNodeContentProps = ComponentProps<typeof motion.div> & {
313 hasChildren?: boolean;
314};
315
316export const TreeNodeContent = ({
317 children,
318 hasChildren = false,
319 className,
320 ...props
321}: TreeNodeContentProps) => {
322 const { animateExpand, expandedIds } = useTree();
323 const { nodeId } = useTreeNode();
324 const isExpanded = expandedIds.has(nodeId);
325
326 return (
327 <AnimatePresence>
328 {hasChildren && isExpanded && (
329 <motion.div
330 animate={{ height: "auto", opacity: 1 }}
331 className="overflow-hidden"
332 exit={{ height: 0, opacity: 0 }}
333 initial={{ height: 0, opacity: 0 }}
334 transition={{
335 duration: animateExpand ? 0.3 : 0,
336 ease: "easeInOut",
337 }}
338 >
339 <motion.div
340 animate={{ y: 0 }}
341 className={className}
342 exit={{ y: -10 }}
343 initial={{ y: -10 }}
344 transition={{
345 duration: animateExpand ? 0.2 : 0,
346 delay: animateExpand ? 0.1 : 0,
347 }}
348 {...props}
349 >
350 {children}
351 </motion.div>
352 </motion.div>
353 )}
354 </AnimatePresence>
355 );
356};
357
358export type TreeExpanderProps = ComponentProps<typeof motion.div> & {
359 hasChildren?: boolean;
360};
361
362export const TreeExpander = ({
363 hasChildren = false,
364 className,
365 onClick,
366 ...props
367}: TreeExpanderProps) => {
368 const { expandedIds, toggleExpanded } = useTree();
369 const { nodeId } = useTreeNode();
370 const isExpanded = expandedIds.has(nodeId);
371
372 if (!hasChildren) {
373 return <div className="mr-1 h-4 w-4" />;
374 }
375
376 return (
377 <motion.div
378 animate={{ rotate: isExpanded ? 90 : 0 }}
379 className={cn(
380 "mr-1 flex h-4 w-4 cursor-pointer items-center justify-center",
381 className
382 )}
383 onClick={(e) => {
384 e.stopPropagation();
385 toggleExpanded(nodeId);
386 onClick?.(e);
387 }}
388 transition={{ duration: 0.2, ease: "easeInOut" }}
389 {...props}
390 >
391 <ChevronRight className="h-3 w-3 text-muted-foreground" />
392 </motion.div>
393 );
394};
395
396export type TreeIconProps = ComponentProps<typeof motion.div> & {
397 icon?: ReactNode;
398 hasChildren?: boolean;
399};
400
401export const TreeIcon = ({
402 icon,
403 hasChildren = false,
404 className,
405 ...props
406}: TreeIconProps) => {
407 const { showIcons, expandedIds } = useTree();
408 const { nodeId } = useTreeNode();
409 const isExpanded = expandedIds.has(nodeId);
410
411 if (!showIcons) {
412 return null;
413 }
414
415 const getDefaultIcon = () =>
416 hasChildren ? (
417 isExpanded ? (
418 <FolderOpen className="h-4 w-4" />
419 ) : (
420 <Folder className="h-4 w-4" />
421 )
422 ) : (
423 <File className="h-4 w-4" />
424 );
425
426 return (
427 <motion.div
428 className={cn(
429 "mr-2 flex h-4 w-4 items-center justify-center text-muted-foreground",
430 className
431 )}
432 transition={{ duration: 0.15 }}
433 whileHover={{ scale: 1.1 }}
434 {...props}
435 >
436 {icon || getDefaultIcon()}
437 </motion.div>
438 );
439};
440
441export type TreeLabelProps = HTMLAttributes<HTMLSpanElement>;
442
443export const TreeLabel = ({ className, ...props }: TreeLabelProps) => (
444 <span className={cn("font flex-1 truncate text-sm", className)} {...props} />
445);
446