import * as AccordionPrimitive from "@radix-ui/react-accordion"; import { cva } from "class-variance-authority"; import { ChevronRight } from "lucide-react"; import { forwardRef, HTMLAttributes, useCallback, useMemo, useState, type ComponentType, type SVGProps, type ReactNode, type ElementRef, type ComponentPropsWithoutRef, type DragEvent, type MouseEvent as ReactMouseEvent, } from "react"; import { cn, createClientOnlyComponent } from "../hooks"; /** * Base CSS variants for tree row visuals. */ const treeVariants = cva( "text-text-primary group hover:before:opacity-100 before:absolute before:rounded-uk-sm before:left-0 before:w-full before:opacity-0 before:bg-bg-secondary before:h-[28px] before:z-0", ); /** Highlight styling when a row is selected. */ const selectedTreeVariants = cva("before:opacity-100 before:bg-brand-primary text-text-withbg"); /** Visual style while an item is a drag-over target. */ const dragOverVariants = cva("before:opacity-100 before:bg-brand-primary/20 text-text-withbg"); type IconComponent = ComponentType>; /** * Tree node data used by `TreeView`. */ interface TreeDataItem { id: string; name: string; icon?: IconComponent; selectedIcon?: IconComponent; openIcon?: IconComponent; children?: TreeDataItem[]; actions?: ReactNode; onClick?: () => void; draggable?: boolean; droppable?: boolean; disabled?: boolean; } /** * Props for the hierarchical tree view component. */ type TreeProps = HTMLAttributes & { data: TreeDataItem[] | TreeDataItem; initialSelectedItemId?: string; onSelectChange?: (item: TreeDataItem | undefined) => void; expandAll?: boolean; defaultNodeIcon?: IconComponent; defaultLeafIcon?: IconComponent; onDocumentDrag?: (sourceItem: TreeDataItem, targetItem: TreeDataItem) => void; }; /** * Interactive tree view supporting expand/collapse and drag-and-drop. */ const TreeViewRoot = forwardRef( ( { data, initialSelectedItemId, onSelectChange, expandAll, defaultLeafIcon, defaultNodeIcon, className, onDocumentDrag, ...props }, ref, ) => { const [selectedItemId, setSelectedItemId] = useState(initialSelectedItemId); const [draggedItem, setDraggedItem] = useState(null); const handleSelectChange = useCallback( (item: TreeDataItem | undefined) => { setSelectedItemId(item?.id); if (onSelectChange) { onSelectChange(item); } }, [onSelectChange], ); const handleDragStart = useCallback((item: TreeDataItem) => { setDraggedItem(item); }, []); const handleDrop = useCallback( (targetItem: TreeDataItem) => { if (draggedItem && onDocumentDrag && draggedItem.id !== targetItem.id) { onDocumentDrag(draggedItem, targetItem); } setDraggedItem(null); }, [draggedItem, onDocumentDrag], ); const expandedItemIds = useMemo(() => { if (!initialSelectedItemId) { return [] as string[]; } const ids: string[] = []; function walkTreeItems(items: TreeDataItem[] | TreeDataItem, targetId: string) { if (items instanceof Array) { for (let i = 0; i < items.length; i++) { ids.push(items[i]!.id); if (walkTreeItems(items[i]!, targetId) && !expandAll) { return true; } if (!expandAll) ids.pop(); } } else if (!expandAll && items.id === targetId) { return true; } else if (items.children) { return walkTreeItems(items.children, targetId); } } walkTreeItems(data, initialSelectedItemId); return ids; }, [data, expandAll, initialSelectedItemId]); return (
{ handleDrop({ id: "", name: "parent_div" }); }} >
); }, ); TreeViewRoot.displayName = "TreeViewRoot"; /** SSR fallback rendering for the tree view. */ const TreeViewFallback = forwardRef( ({ data, initialSelectedItemId, onSelectChange, className, ...props }, ref) => { const [selectedItemId, setSelectedItemId] = useState(initialSelectedItemId); const dataArray = Array.isArray(data) ? data : [data]; return (
    {dataArray.map((item) => (
  • { setSelectedItemId(item.id); onSelectChange?.(item); item.onClick?.(); }} > {item.name}
  • ))}
); }, ); TreeViewFallback.displayName = "TreeViewFallback"; const TreeView = createClientOnlyComponent(TreeViewRoot, TreeViewFallback); type TreeItemProps = TreeProps & { selectedItemId?: string; handleSelectChange: (item: TreeDataItem | undefined) => void; expandedItemIds: string[]; defaultNodeIcon?: IconComponent; defaultLeafIcon?: IconComponent; handleDragStart?: (item: TreeDataItem) => void; handleDrop?: (item: TreeDataItem) => void; draggedItem: TreeDataItem | null; }; /** * Internal renderer that maps an item or array into nodes/leaves. */ const TreeItem = forwardRef( ( { className, data, selectedItemId, handleSelectChange, expandedItemIds, defaultNodeIcon, defaultLeafIcon, handleDragStart, handleDrop, draggedItem, ...props }, ref, ) => { if (!(data instanceof Array)) { data = [data]; } return (
    {data.map((item) => (
  • {item.children ? ( ) : ( )}
  • ))}
); }, ); TreeItem.displayName = "TreeItem"; /** * A node item that can expand to show children. */ const TreeNode = ({ item, handleSelectChange, expandedItemIds, selectedItemId, defaultNodeIcon, defaultLeafIcon, handleDragStart, handleDrop, draggedItem, }: { item: TreeDataItem; handleSelectChange: (item: TreeDataItem | undefined) => void; expandedItemIds: string[]; selectedItemId?: string; defaultNodeIcon?: IconComponent; defaultLeafIcon?: IconComponent; handleDragStart?: (item: TreeDataItem) => void; handleDrop?: (item: TreeDataItem) => void; draggedItem: TreeDataItem | null; }) => { const [value, setValue] = useState(expandedItemIds.includes(item.id) ? [item.id] : []); const [isDragOver, setIsDragOver] = useState(false); const onDragStart = (e: DragEvent) => { if (!item.draggable) { e.preventDefault(); return; } e.dataTransfer.setData("text/plain", item.id); handleDragStart?.(item); }; const onDragOver = (e: DragEvent) => { if (item.droppable !== false && draggedItem && draggedItem.id !== item.id) { e.preventDefault(); setIsDragOver(true); } }; const onDragLeave = () => { setIsDragOver(false); }; const onDrop = (e: DragEvent) => { e.preventDefault(); setIsDragOver(false); handleDrop?.(item); }; const handleSelect = () => { handleSelectChange(item); item.onClick?.(); }; return ( setValue(s)}>
{ e.stopPropagation(); }} > { e.stopPropagation(); handleSelect(); }} item={item} isSelected={selectedItemId === item.id} isOpen={value.includes(item.id)} default={defaultNodeIcon} /> { e.stopPropagation(); handleSelect(); }} > {item.name} { e.stopPropagation(); }} > {item.actions}
); }; /** * A leaf item without children. */ const TreeLeaf = forwardRef< HTMLDivElement, HTMLAttributes & { item: TreeDataItem; selectedItemId?: string; handleSelectChange: (item: TreeDataItem | undefined) => void; defaultLeafIcon?: IconComponent; handleDragStart?: (item: TreeDataItem) => void; handleDrop?: (item: TreeDataItem) => void; draggedItem: TreeDataItem | null; } >( ( { className, item, selectedItemId, handleSelectChange, defaultLeafIcon, handleDragStart, handleDrop, draggedItem, ...props }, ref, ) => { const [isDragOver, setIsDragOver] = useState(false); const onDragStart = (e: DragEvent) => { if (!item.draggable || item.disabled) { e.preventDefault(); return; } e.dataTransfer.setData("text/plain", item.id); handleDragStart?.(item); }; const onDragOver = (e: DragEvent) => { if (item.droppable !== false && !item.disabled && draggedItem && draggedItem.id !== item.id) { e.preventDefault(); setIsDragOver(true); } }; const onDragLeave = () => { setIsDragOver(false); }; const onDrop = (e: DragEvent) => { if (item.disabled) return; e.preventDefault(); setIsDragOver(false); handleDrop?.(item); }; return (
{ if (item.disabled) return; handleSelectChange(item); item.onClick?.(); }} draggable={!!item.draggable && !item.disabled} onDragStart={onDragStart} onDragOver={onDragOver} onDragLeave={onDragLeave} onDrop={onDrop} {...props} > {item.name} {item.actions}
); }, ); TreeLeaf.displayName = "TreeLeaf"; /** * Styled trigger for collapsible node rows. */ const AccordionTrigger = forwardRef< ElementRef, ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( svg]:rotate-90", className, )} {...props} > {children} )); AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName; /** * Styled content area for nested children. */ const AccordionContent = forwardRef< ElementRef, ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => (
{children}
)); AccordionContent.displayName = AccordionPrimitive.Content.displayName; /** * Chooses the most appropriate icon based on selection/open state. */ const TreeIcon = ({ item, isOpen, isSelected, default: defaultIcon, onClick, }: { item: TreeDataItem; isOpen?: boolean; isSelected?: boolean; default?: IconComponent; onClick?: (e: ReactMouseEvent) => void; }) => { let Icon = defaultIcon; if (isSelected && item.selectedIcon) { Icon = item.selectedIcon; } else if (isOpen && item.openIcon) { Icon = item.openIcon; } else if (item.icon) { Icon = item.icon; } return Icon ? : <>; }; /** * Right-aligned action slot shown when row is active/selected. */ const TreeActions = ({ children, isSelected, onClick, }: { children: ReactNode; isSelected: boolean; onClick?: (e: ReactMouseEvent) => void; }) => { return (
{children}
); }; export { TreeView as SimpleTreeView, type TreeDataItem as SimpleTreeDataItem };