Skip to content

UI Library for Design Engineers. Animated components and effects you can copy and paste into your apps. Free. Open Source.

feat(file-tree): add auto-sorted elements mode to file-tree (#921)

Yeom-JinHo6993c0aa3b1b
diff --git a/apps/www/content/docs/components/file-tree.mdx b/apps/www/content/docs/components/file-tree.mdx
index 23f0c6b1..271babee 100644
--- a/apps/www/content/docs/components/file-tree.mdx
+++ b/apps/www/content/docs/components/file-tree.mdx
@@ -43,33 +43,54 @@ npx shadcn@latest add @magicui/file-tree
## Usage
```tsx showLineNumbers
-import { File, Folder, Tree } from "@/components/ui/file-tree"
+import { Tree } from "@/components/ui/file-tree"
+import type { TreeViewElement } from "@/components/ui/file-tree"
```
```tsx showLineNumbers
-<Tree>
- <Folder>
- <Folder>
- <File>layout.tsx</File>
- <File>page.tsx</File>
- </Folder>
- </Folder>
-</Tree>
+const elements: TreeViewElement[] = [
+ {
+ id: "src",
+ type: "folder",
+ name: "src",
+ children: [
+ { id: "components", type: "folder", name: "components" },
+ { id: "app", type: "folder", name: "app" },
+ { id: "page", name: "page.tsx" },
+ { id: "layout", name: "layout.tsx" },
+ ],
+ },
+]
+
+<Tree elements={elements} />
```
+When you pass `elements` and omit `children`, the tree is rendered from data and siblings are sorted automatically using a folders-first alphabetical order. Use `sort="none"` to preserve the input order, or pass a custom comparator.
+
## Props
### Tree
-| Prop | Type | Default | Description |
-| ---------------------- | ------------------- | ------- | ------------------------------------------------------------ |
-| `initialSelectedId` | `string` | `-` | The ID of the initially selected item. |
-| `indicator` | `boolean` | `true` | Whether to show the tree indicator line. |
-| `elements` | `TreeViewElement[]` | `-` | An array of tree view elements to render. |
-| `initialExpandedItems` | `string[]` | `-` | An array of IDs for items that should be initially expanded. |
-| `openIcon` | `React.ReactNode` | `-` | Custom icon for open folders. |
-| `closeIcon` | `React.ReactNode` | `-` | Custom icon for closed folders. |
-| `dir` | `"rtl" \| "ltr"` | `"ltr"` | The text direction of the tree. |
+| Prop | Type | Default | Description |
+| ---------------------- | ------------------------------------------- | ----------- | --------------------------------------------------------------------- |
+| `initialSelectedId` | `string` | `-` | The ID of the initially selected item. |
+| `indicator` | `boolean` | `true` | Whether to show the tree indicator line. |
+| `elements` | `TreeViewElement[]` | `-` | An array of tree view elements to render when `children` are omitted. |
+| `initialExpandedItems` | `string[]` | `-` | An array of IDs for items that should be initially expanded. |
+| `openIcon` | `React.ReactNode` | `-` | Custom icon for open folders. |
+| `closeIcon` | `React.ReactNode` | `-` | Custom icon for closed folders. |
+| `sort` | `"default" \| "none" \| ((a, b) => number)` | `"default"` | Sorting mode used for data-driven trees rendered from `elements`. |
+| `dir` | `"rtl" \| "ltr"` | `"ltr"` | The text direction of the tree. |
+
+### TreeViewElement
+
+| Prop | Type | Default | Description |
+| -------------- | -------------------- | ------- | ----------------------------------------------------- |
+| `id` | `string` | `-` | A unique identifier for the node. |
+| `name` | `string` | `-` | The label rendered for the node in data-driven mode. |
+| `type` | `"file" \| "folder"` | `-` | Explicit node type. Use `"folder"` for empty folders. |
+| `isSelectable` | `boolean` | `true` | Whether the node can be selected. |
+| `children` | `TreeViewElement[]` | `-` | Child nodes for folders. |
### Folder
diff --git a/apps/www/public/llms-full.txt b/apps/www/public/llms-full.txt
index 88d530f2..12d42b82 100644
--- a/apps/www/public/llms-full.txt
+++ b/apps/www/public/llms-full.txt
@@ -6526,10 +6526,16 @@ import { ScrollArea } from "@/components/ui/scroll-area"
type TreeViewElement = {
id: string
name: string
+ type?: "file" | "folder"
isSelectable?: boolean
children?: TreeViewElement[]
}
+type TreeSortMode =
+ | "default"
+ | "none"
+ | ((a: TreeViewElement, b: TreeViewElement) => number)
+
type TreeContextProps = {
selectedId: string | undefined
expandedItems: string[] | undefined
@@ -6554,6 +6560,102 @@ const useTree = () => {
type Direction = "rtl" | "ltr" | undefined
+const isFolderElement = (element: TreeViewElement) => {
+ if (element.type) {
+ return element.type === "folder"
+ }
+
+ return Array.isArray(element.children)
+}
+
+const mergeExpandedItems = (
+ currentItems: string[] | undefined,
+ nextItems: string[]
+) => [...new Set([...(currentItems ?? []), ...nextItems])]
+
+const treeCollator = new Intl.Collator("en", {
+ numeric: true,
+ sensitivity: "base",
+})
+
+const defaultTreeComparator = (a: TreeViewElement, b: TreeViewElement) => {
+ const aIsFolder = isFolderElement(a)
+ const bIsFolder = isFolderElement(b)
+
+ if (aIsFolder !== bIsFolder) {
+ return aIsFolder ? -1 : 1
+ }
+
+ return treeCollator.compare(a.name, b.name)
+}
+
+const getTreeComparator = (sort: TreeSortMode) => {
+ if (sort === "none") {
+ return undefined
+ }
+
+ if (sort === "default") {
+ return defaultTreeComparator
+ }
+
+ return sort
+}
+
+const sortTreeElements = (
+ elements: TreeViewElement[],
+ sort: TreeSortMode
+): TreeViewElement[] => {
+ const comparator = getTreeComparator(sort)
+
+ const nextElements = elements.map((element) => {
+ if (!Array.isArray(element.children)) {
+ return element
+ }
+
+ return {
+ ...element,
+ children: sortTreeElements(element.children, sort),
+ }
+ })
+
+ if (!comparator) {
+ return nextElements
+ }
+
+ return [...nextElements].sort(comparator)
+}
+
+const renderTreeElements = (
+ elements: TreeViewElement[],
+ sort: TreeSortMode
+): React.ReactNode =>
+ sortTreeElements(elements, sort).map((element) => {
+ if (isFolderElement(element)) {
+ return (
+ <Folder
+ key={element.id}
+ value={element.id}
+ element={element.name}
+ isSelectable={element.isSelectable}
+ >
+ {Array.isArray(element.children)
+ ? renderTreeElements(element.children, sort)
+ : null}
+ </Folder>
+ )
+ }
+
+ return (
+ <File
+ key={element.id}
+ value={element.id}
+ isSelectable={element.isSelectable}
+ >
+ <span>{element.name}</span>
+ </File>
+ )
+ })
+
type TreeViewProps = {
initialSelectedId?: string
indicator?: boolean
@@ -6561,7 +6663,11 @@ type TreeViewProps = {
initialExpandedItems?: string[]
openIcon?: React.ReactNode
closeIcon?: React.ReactNode
-} & React.HTMLAttributes<HTMLDivElement>
+ sort?: TreeSortMode
+} & Omit<
+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Root>,
+ "defaultValue" | "onValueChange" | "type" | "value"
+>
const Tree = forwardRef<HTMLDivElement, TreeViewProps>(
(
@@ -6574,6 +6680,7 @@ const Tree = forwardRef<HTMLDivElement, TreeViewProps>(
indicator = true,
openIcon,
closeIcon,
+ sort = "default",
dir,
...props
},
@@ -6610,18 +6717,17 @@ const Tree = forwardRef<HTMLDivElement, TreeViewProps>(
const newPath = [...currentPath, currentElement.id]
if (currentElement.id === selectId) {
if (isSelectable) {
- setExpandedItems((prev) => [...(prev ?? []), ...newPath])
+ setExpandedItems((prev) => mergeExpandedItems(prev, newPath))
} else {
if (newPath.includes(currentElement.id)) {
newPath.pop()
- setExpandedItems((prev) => [...(prev ?? []), ...newPath])
+ setExpandedItems((prev) => mergeExpandedItems(prev, newPath))
}
}
return
}
if (
- isSelectable &&
- currentElement.children &&
+ Array.isArray(currentElement.children) &&
currentElement.children.length > 0
) {
currentElement.children.forEach((child) => {
@@ -6643,6 +6749,8 @@ const Tree = forwardRef<HTMLDivElement, TreeViewProps>(
}, [initialSelectedId, elements, expandSpecificTargetedElements])
const direction = dir === "rtl" ? "rtl" : "ltr"
+ const treeChildren =
+ children ?? (elements ? renderTreeElements(elements, sort) : null)
return (
<TreeContext.Provider
@@ -6667,15 +6775,11 @@ const Tree = forwardRef<HTMLDivElement, TreeViewProps>(
<AccordionPrimitive.Root
{...props}
type="multiple"
- defaultValue={expandedItems}
value={expandedItems}
className="flex flex-col gap-1"
- onValueChange={(value) =>
- setExpandedItems((prev) => [...(prev ?? []), value[0]])
- }
dir={dir as Direction}
>
- {children}
+ {treeChildren}
</AccordionPrimitive.Root>
</ScrollArea>
</div>
@@ -6735,10 +6839,12 @@ const Folder = forwardRef<
handleExpand,
expandedItems,
indicator,
- setExpandedItems,
+ selectedId,
+ selectItem,
openIcon,
closeIcon,
} = useTree()
+ const isSelected = isSelect ?? selectedId === value
return (
<AccordionPrimitive.Item
@@ -6752,13 +6858,16 @@ const Folder = forwardRef<
`flex items-center gap-1 rounded-md text-sm`,
className,
{
- "bg-muted rounded-md": isSelect && isSelectable,
+ "bg-muted rounded-md": isSelected && isSelectable,
"cursor-pointer": isSelectable,
"cursor-not-allowed opacity-50": !isSelectable,
}
)}
disabled={!isSelectable}
- onClick={() => handleExpand(value)}
+ onClick={() => {
+ selectItem(value)
+ handleExpand(value)
+ }}
>
{expandedItems?.includes(value)
? (openIcon ?? <FolderOpenIcon className="size-4" />)
@@ -6771,11 +6880,7 @@ const Folder = forwardRef<
dir={direction}
type="multiple"
className="ml-5 flex flex-col gap-1 py-1 rtl:mr-5"
- defaultValue={expandedItems}
value={expandedItems}
- onValueChange={(value) => {
- setExpandedItems?.((prev) => [...(prev ?? []), value[0]])
- }}
>
{children}
</AccordionPrimitive.Root>
@@ -6903,117 +7008,95 @@ const CollapseButton = forwardRef<
CollapseButton.displayName = "CollapseButton"
export { CollapseButton, File, Folder, Tree, type TreeViewElement }
+export type { TreeSortMode }
===== EXAMPLE: file-tree-demo =====
Title: File Tree Demo
--- file: example/file-tree-demo.tsx ---
-import { File, Folder, Tree } from "@/registry/magicui/file-tree"
+import { Tree } from "@/registry/magicui/file-tree"
+import type { TreeViewElement } from "@/registry/magicui/file-tree"
export default function FileTreeDemo() {
return (
- <div className="bg-background relative flex h-[300px] w-1/2 flex-col items-center justify-center overflow-hidden rounded-lg border">
+ <div className="bg-background relative flex h-[300px] w-full max-w-sm flex-col items-center justify-center overflow-hidden rounded-lg border">
<Tree
className="bg-background overflow-hidden rounded-md p-2"
- initialSelectedId="7"
- initialExpandedItems={[
- "1",
- "2",
- "3",
- "4",
- "5",
- "6",
- "7",
- "8",
- "9",
- "10",
- "11",
- ]}
+ initialSelectedId="button"
+ initialExpandedItems={["src", "app", "components", "ui", "lib"]}
elements={ELEMENTS}
- >
- <Folder element="src" value="1">
- <Folder value="2" element="app">
- <File value="3">
- <p>layout.tsx</p>
- </File>
- <File value="4">
- <p>page.tsx</p>
- </File>
- </Folder>
- <Folder value="5" element="components">
- <Folder value="6" element="ui">
- <File value="7">
- <p>button.tsx</p>
- </File>
- </Folder>
- <File value="8">
- <p>header.tsx</p>
- </File>
- <File value="9">
- <p>footer.tsx</p>
- </File>
- </Folder>
- <Folder value="10" element="lib">
- <File value="11">
- <p>utils.ts</p>
- </File>
- </Folder>
- </Folder>
- </Tree>
+ />
</div>
)
}
-const ELEMENTS = [
+const ELEMENTS: TreeViewElement[] = [
{
- id: "1",
+ id: "src",
+ type: "folder",
isSelectable: true,
name: "src",
children: [
{
- id: "2",
+ id: "lib",
+ type: "folder",
isSelectable: true,
- name: "app",
+ name: "lib",
children: [
{
- id: "3",
+ id: "utils",
isSelectable: true,
- name: "layout.tsx",
+ name: "utils.ts",
},
+ ],
+ },
+ {
+ id: "app",
+ type: "folder",
+ isSelectable: true,
+ name: "app",
+ children: [
{
- id: "4",
+ id: "page",
isSelectable: true,
name: "page.tsx",
},
+ {
+ id: "layout",
+ isSelectable: true,
+ name: "layout.tsx",
+ },
],
},
{
- id: "5",
+ id: "components",
+ type: "folder",
isSelectable: true,
name: "components",
children: [
{
- id: "6",
+ id: "header",
isSelectable: true,
name: "header.tsx",
},
{
- id: "7",
+ id: "ui",
+ type: "folder",
isSelectable: true,
- name: "footer.tsx",
+ name: "ui",
+ children: [
+ {
+ id: "button",
+ isSelectable: true,
+ name: "button.tsx",
+ },
+ ],
},
- ],
- },
- {
- id: "8",
- isSelectable: true,
- name: "lib",
- children: [
{
- id: "9",
+ id: "footer",
isSelectable: true,
- name: "utils.ts",
+ name: "footer.tsx",
},
],
},
diff --git a/apps/www/public/r/file-tree-demo.json b/apps/www/public/r/file-tree-demo.json
index 842bf545..1b9f5bd3 100644
--- a/apps/www/public/r/file-tree-demo.json
+++ b/apps/www/public/r/file-tree-demo.json
@@ -10,7 +10,7 @@
"files": [
{
"path": "registry/example/file-tree-demo.tsx",
- "content": "import { File, Folder, Tree } from \"@/registry/magicui/file-tree\"\n\nexport default function FileTreeDemo() {\n return (\n <div className=\"bg-background relative flex h-[300px] w-1/2 flex-col items-center justify-center overflow-hidden rounded-lg border\">\n <Tree\n className=\"bg-background overflow-hidden rounded-md p-2\"\n initialSelectedId=\"7\"\n initialExpandedItems={[\n \"1\",\n \"2\",\n \"3\",\n \"4\",\n \"5\",\n \"6\",\n \"7\",\n \"8\",\n \"9\",\n \"10\",\n \"11\",\n ]}\n elements={ELEMENTS}\n >\n <Folder element=\"src\" value=\"1\">\n <Folder value=\"2\" element=\"app\">\n <File value=\"3\">\n <p>layout.tsx</p>\n </File>\n <File value=\"4\">\n <p>page.tsx</p>\n </File>\n </Folder>\n <Folder value=\"5\" element=\"components\">\n <Folder value=\"6\" element=\"ui\">\n <File value=\"7\">\n <p>button.tsx</p>\n </File>\n </Folder>\n <File value=\"8\">\n <p>header.tsx</p>\n </File>\n <File value=\"9\">\n <p>footer.tsx</p>\n </File>\n </Folder>\n <Folder value=\"10\" element=\"lib\">\n <File value=\"11\">\n <p>utils.ts</p>\n </File>\n </Folder>\n </Folder>\n </Tree>\n </div>\n )\n}\n\nconst ELEMENTS = [\n {\n id: \"1\",\n isSelectable: true,\n name: \"src\",\n children: [\n {\n id: \"2\",\n isSelectable: true,\n name: \"app\",\n children: [\n {\n id: \"3\",\n isSelectable: true,\n name: \"layout.tsx\",\n },\n {\n id: \"4\",\n isSelectable: true,\n name: \"page.tsx\",\n },\n ],\n },\n {\n id: \"5\",\n isSelectable: true,\n name: \"components\",\n children: [\n {\n id: \"6\",\n isSelectable: true,\n name: \"header.tsx\",\n },\n {\n id: \"7\",\n isSelectable: true,\n name: \"footer.tsx\",\n },\n ],\n },\n {\n id: \"8\",\n isSelectable: true,\n name: \"lib\",\n children: [\n {\n id: \"9\",\n isSelectable: true,\n name: \"utils.ts\",\n },\n ],\n },\n ],\n },\n]\n",
+ "content": "import { Tree } from \"@/registry/magicui/file-tree\"\nimport type { TreeViewElement } from \"@/registry/magicui/file-tree\"\n\nexport default function FileTreeDemo() {\n return (\n <div className=\"bg-background relative flex h-[300px] w-full max-w-sm flex-col items-center justify-center overflow-hidden rounded-lg border\">\n <Tree\n className=\"bg-background overflow-hidden rounded-md p-2\"\n initialSelectedId=\"button\"\n initialExpandedItems={[\"src\", \"app\", \"components\", \"ui\", \"lib\"]}\n elements={ELEMENTS}\n />\n </div>\n )\n}\n\nconst ELEMENTS: TreeViewElement[] = [\n {\n id: \"src\",\n type: \"folder\",\n isSelectable: true,\n name: \"src\",\n children: [\n {\n id: \"lib\",\n type: \"folder\",\n isSelectable: true,\n name: \"lib\",\n children: [\n {\n id: \"utils\",\n isSelectable: true,\n name: \"utils.ts\",\n },\n ],\n },\n {\n id: \"app\",\n type: \"folder\",\n isSelectable: true,\n name: \"app\",\n children: [\n {\n id: \"page\",\n isSelectable: true,\n name: \"page.tsx\",\n },\n {\n id: \"layout\",\n isSelectable: true,\n name: \"layout.tsx\",\n },\n ],\n },\n {\n id: \"components\",\n type: \"folder\",\n isSelectable: true,\n name: \"components\",\n children: [\n {\n id: \"header\",\n isSelectable: true,\n name: \"header.tsx\",\n },\n {\n id: \"ui\",\n type: \"folder\",\n isSelectable: true,\n name: \"ui\",\n children: [\n {\n id: \"button\",\n isSelectable: true,\n name: \"button.tsx\",\n },\n ],\n },\n {\n id: \"footer\",\n isSelectable: true,\n name: \"footer.tsx\",\n },\n ],\n },\n ],\n },\n]\n",
"type": "registry:example"
}
]
diff --git a/apps/www/public/r/file-tree.json b/apps/www/public/r/file-tree.json
index 89a2802a..3084f7c2 100644
--- a/apps/www/public/r/file-tree.json
+++ b/apps/www/public/r/file-tree.json
@@ -7,7 +7,7 @@
"files": [
{
"path": "registry/magicui/file-tree.tsx",
- "content": "\"use client\"\n\nimport React, {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\"\nimport * as AccordionPrimitive from \"@radix-ui/react-accordion\"\nimport { FileIcon, FolderIcon, FolderOpenIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport { ScrollArea } from \"@/components/ui/scroll-area\"\n\ntype TreeViewElement = {\n id: string\n name: string\n isSelectable?: boolean\n children?: TreeViewElement[]\n}\n\ntype TreeContextProps = {\n selectedId: string | undefined\n expandedItems: string[] | undefined\n indicator: boolean\n handleExpand: (id: string) => void\n selectItem: (id: string) => void\n setExpandedItems?: React.Dispatch<React.SetStateAction<string[] | undefined>>\n openIcon?: React.ReactNode\n closeIcon?: React.ReactNode\n direction: \"rtl\" | \"ltr\"\n}\n\nconst TreeContext = createContext<TreeContextProps | null>(null)\n\nconst useTree = () => {\n const context = useContext(TreeContext)\n if (!context) {\n throw new Error(\"useTree must be used within a TreeProvider\")\n }\n return context\n}\n\ntype Direction = \"rtl\" | \"ltr\" | undefined\n\ntype TreeViewProps = {\n initialSelectedId?: string\n indicator?: boolean\n elements?: TreeViewElement[]\n initialExpandedItems?: string[]\n openIcon?: React.ReactNode\n closeIcon?: React.ReactNode\n} & React.HTMLAttributes<HTMLDivElement>\n\nconst Tree = forwardRef<HTMLDivElement, TreeViewProps>(\n (\n {\n className,\n elements,\n initialSelectedId,\n initialExpandedItems,\n children,\n indicator = true,\n openIcon,\n closeIcon,\n dir,\n ...props\n },\n ref\n ) => {\n const [selectedId, setSelectedId] = useState<string | undefined>(\n initialSelectedId\n )\n const [expandedItems, setExpandedItems] = useState<string[] | undefined>(\n initialExpandedItems\n )\n\n const selectItem = useCallback((id: string) => {\n setSelectedId(id)\n }, [])\n\n const handleExpand = useCallback((id: string) => {\n setExpandedItems((prev) => {\n if (prev?.includes(id)) {\n return prev.filter((item) => item !== id)\n }\n return [...(prev ?? []), id]\n })\n }, [])\n\n const expandSpecificTargetedElements = useCallback(\n (elements?: TreeViewElement[], selectId?: string) => {\n if (!elements || !selectId) return\n const findParent = (\n currentElement: TreeViewElement,\n currentPath: string[] = []\n ) => {\n const isSelectable = currentElement.isSelectable ?? true\n const newPath = [...currentPath, currentElement.id]\n if (currentElement.id === selectId) {\n if (isSelectable) {\n setExpandedItems((prev) => [...(prev ?? []), ...newPath])\n } else {\n if (newPath.includes(currentElement.id)) {\n newPath.pop()\n setExpandedItems((prev) => [...(prev ?? []), ...newPath])\n }\n }\n return\n }\n if (\n isSelectable &&\n currentElement.children &&\n currentElement.children.length > 0\n ) {\n currentElement.children.forEach((child) => {\n findParent(child, newPath)\n })\n }\n }\n elements.forEach((element) => {\n findParent(element)\n })\n },\n []\n )\n\n useEffect(() => {\n if (initialSelectedId) {\n expandSpecificTargetedElements(elements, initialSelectedId)\n }\n }, [initialSelectedId, elements, expandSpecificTargetedElements])\n\n const direction = dir === \"rtl\" ? \"rtl\" : \"ltr\"\n\n return (\n <TreeContext.Provider\n value={{\n selectedId,\n expandedItems,\n handleExpand,\n selectItem,\n setExpandedItems,\n indicator,\n openIcon,\n closeIcon,\n direction,\n }}\n >\n <div className={cn(\"size-full\", className)}>\n <ScrollArea\n ref={ref}\n className=\"relative h-full px-2\"\n dir={dir as Direction}\n >\n <AccordionPrimitive.Root\n {...props}\n type=\"multiple\"\n defaultValue={expandedItems}\n value={expandedItems}\n className=\"flex flex-col gap-1\"\n onValueChange={(value) =>\n setExpandedItems((prev) => [...(prev ?? []), value[0]])\n }\n dir={dir as Direction}\n >\n {children}\n </AccordionPrimitive.Root>\n </ScrollArea>\n </div>\n </TreeContext.Provider>\n )\n }\n)\n\nTree.displayName = \"Tree\"\n\nconst TreeIndicator = forwardRef<\n HTMLDivElement,\n React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => {\n const { direction } = useTree()\n\n return (\n <div\n dir={direction}\n ref={ref}\n className={cn(\n \"bg-muted absolute left-1.5 h-full w-px rounded-md py-3 duration-300 ease-in-out hover:bg-slate-300 rtl:right-1.5\",\n className\n )}\n {...props}\n />\n )\n})\n\nTreeIndicator.displayName = \"TreeIndicator\"\n\ntype FolderProps = {\n expandedItems?: string[]\n element: string\n isSelectable?: boolean\n isSelect?: boolean\n} & React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>\n\nconst Folder = forwardRef<\n HTMLDivElement,\n FolderProps & React.HTMLAttributes<HTMLDivElement>\n>(\n (\n {\n className,\n element,\n value,\n isSelectable = true,\n isSelect,\n children,\n ...props\n },\n ref\n ) => {\n const {\n direction,\n handleExpand,\n expandedItems,\n indicator,\n setExpandedItems,\n openIcon,\n closeIcon,\n } = useTree()\n\n return (\n <AccordionPrimitive.Item\n ref={ref}\n {...props}\n value={value}\n className=\"relative h-full overflow-hidden\"\n >\n <AccordionPrimitive.Trigger\n className={cn(\n `flex items-center gap-1 rounded-md text-sm`,\n className,\n {\n \"bg-muted rounded-md\": isSelect && isSelectable,\n \"cursor-pointer\": isSelectable,\n \"cursor-not-allowed opacity-50\": !isSelectable,\n }\n )}\n disabled={!isSelectable}\n onClick={() => handleExpand(value)}\n >\n {expandedItems?.includes(value)\n ? (openIcon ?? <FolderOpenIcon className=\"size-4\" />)\n : (closeIcon ?? <FolderIcon className=\"size-4\" />)}\n <span>{element}</span>\n </AccordionPrimitive.Trigger>\n <AccordionPrimitive.Content className=\"data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down relative h-full overflow-hidden text-sm\">\n {element && indicator && <TreeIndicator aria-hidden=\"true\" />}\n <AccordionPrimitive.Root\n dir={direction}\n type=\"multiple\"\n className=\"ml-5 flex flex-col gap-1 py-1 rtl:mr-5\"\n defaultValue={expandedItems}\n value={expandedItems}\n onValueChange={(value) => {\n setExpandedItems?.((prev) => [...(prev ?? []), value[0]])\n }}\n >\n {children}\n </AccordionPrimitive.Root>\n </AccordionPrimitive.Content>\n </AccordionPrimitive.Item>\n )\n }\n)\n\nFolder.displayName = \"Folder\"\n\nconst File = forwardRef<\n HTMLButtonElement,\n {\n value: string\n handleSelect?: (id: string) => void\n isSelectable?: boolean\n isSelect?: boolean\n fileIcon?: React.ReactNode\n } & React.ButtonHTMLAttributes<HTMLButtonElement>\n>(\n (\n {\n value,\n className,\n handleSelect,\n onClick,\n isSelectable = true,\n isSelect,\n fileIcon,\n children,\n ...props\n },\n ref\n ) => {\n const { direction, selectedId, selectItem } = useTree()\n const isSelected = isSelect ?? selectedId === value\n return (\n <button\n ref={ref}\n type=\"button\"\n disabled={!isSelectable}\n className={cn(\n \"flex w-fit items-center gap-1 rounded-md pr-1 text-sm duration-200 ease-in-out rtl:pr-0 rtl:pl-1\",\n {\n \"bg-muted\": isSelected && isSelectable,\n },\n isSelectable ? \"cursor-pointer\" : \"cursor-not-allowed opacity-50\",\n direction === \"rtl\" ? \"rtl\" : \"ltr\",\n className\n )}\n onClick={(event) => {\n selectItem(value)\n handleSelect?.(value)\n onClick?.(event)\n }}\n {...props}\n >\n {fileIcon ?? <FileIcon className=\"size-4\" />}\n {children}\n </button>\n )\n }\n)\n\nFile.displayName = \"File\"\n\nconst CollapseButton = forwardRef<\n HTMLButtonElement,\n {\n elements: TreeViewElement[]\n expandAll?: boolean\n } & React.HTMLAttributes<HTMLButtonElement>\n>(({ className, elements, expandAll = false, children, ...props }, ref) => {\n const { expandedItems, setExpandedItems } = useTree()\n\n const expendAllTree = useCallback((elements: TreeViewElement[]) => {\n const expandedElementIds: string[] = []\n\n const expandTree = (element: TreeViewElement) => {\n const isSelectable = element.isSelectable ?? true\n if (isSelectable && element.children && element.children.length > 0) {\n expandedElementIds.push(element.id)\n for (const child of element.children) {\n expandTree(child)\n }\n }\n }\n\n for (const element of elements) {\n expandTree(element)\n }\n\n return [...new Set(expandedElementIds)]\n }, [])\n\n const closeAll = useCallback(() => {\n setExpandedItems?.([])\n }, [setExpandedItems])\n\n useEffect(() => {\n if (expandAll) {\n setExpandedItems?.(expendAllTree(elements))\n }\n }, [expandAll, elements, expendAllTree, setExpandedItems])\n\n return (\n <Button\n variant={\"ghost\"}\n className={cn(\"absolute right-2 bottom-1 h-8 w-fit p-1\", className)}\n onClick={\n expandedItems && expandedItems.length > 0\n ? closeAll\n : () => setExpandedItems?.(expendAllTree(elements))\n }\n ref={ref}\n {...props}\n >\n {children}\n <span className=\"sr-only\">Toggle</span>\n </Button>\n )\n})\n\nCollapseButton.displayName = \"CollapseButton\"\n\nexport { CollapseButton, File, Folder, Tree, type TreeViewElement }\n",
+ "content": "\"use client\"\n\nimport React, {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\"\nimport * as AccordionPrimitive from \"@radix-ui/react-accordion\"\nimport { FileIcon, FolderIcon, FolderOpenIcon } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport { ScrollArea } from \"@/components/ui/scroll-area\"\n\ntype TreeViewElement = {\n id: string\n name: string\n type?: \"file\" | \"folder\"\n isSelectable?: boolean\n children?: TreeViewElement[]\n}\n\ntype TreeSortMode =\n | \"default\"\n | \"none\"\n | ((a: TreeViewElement, b: TreeViewElement) => number)\n\ntype TreeContextProps = {\n selectedId: string | undefined\n expandedItems: string[] | undefined\n indicator: boolean\n handleExpand: (id: string) => void\n selectItem: (id: string) => void\n setExpandedItems?: React.Dispatch<React.SetStateAction<string[] | undefined>>\n openIcon?: React.ReactNode\n closeIcon?: React.ReactNode\n direction: \"rtl\" | \"ltr\"\n}\n\nconst TreeContext = createContext<TreeContextProps | null>(null)\n\nconst useTree = () => {\n const context = useContext(TreeContext)\n if (!context) {\n throw new Error(\"useTree must be used within a TreeProvider\")\n }\n return context\n}\n\ntype Direction = \"rtl\" | \"ltr\" | undefined\n\nconst isFolderElement = (element: TreeViewElement) => {\n if (element.type) {\n return element.type === \"folder\"\n }\n\n return Array.isArray(element.children)\n}\n\nconst mergeExpandedItems = (\n currentItems: string[] | undefined,\n nextItems: string[]\n) => [...new Set([...(currentItems ?? []), ...nextItems])]\n\nconst treeCollator = new Intl.Collator(\"en\", {\n numeric: true,\n sensitivity: \"base\",\n})\n\nconst defaultTreeComparator = (a: TreeViewElement, b: TreeViewElement) => {\n const aIsFolder = isFolderElement(a)\n const bIsFolder = isFolderElement(b)\n\n if (aIsFolder !== bIsFolder) {\n return aIsFolder ? -1 : 1\n }\n\n return treeCollator.compare(a.name, b.name)\n}\n\nconst getTreeComparator = (sort: TreeSortMode) => {\n if (sort === \"none\") {\n return undefined\n }\n\n if (sort === \"default\") {\n return defaultTreeComparator\n }\n\n return sort\n}\n\nconst sortTreeElements = (\n elements: TreeViewElement[],\n sort: TreeSortMode\n): TreeViewElement[] => {\n const comparator = getTreeComparator(sort)\n\n const nextElements = elements.map((element) => {\n if (!Array.isArray(element.children)) {\n return element\n }\n\n return {\n ...element,\n children: sortTreeElements(element.children, sort),\n }\n })\n\n if (!comparator) {\n return nextElements\n }\n\n return [...nextElements].sort(comparator)\n}\n\nconst renderTreeElements = (\n elements: TreeViewElement[],\n sort: TreeSortMode\n): React.ReactNode =>\n sortTreeElements(elements, sort).map((element) => {\n if (isFolderElement(element)) {\n return (\n <Folder\n key={element.id}\n value={element.id}\n element={element.name}\n isSelectable={element.isSelectable}\n >\n {Array.isArray(element.children)\n ? renderTreeElements(element.children, sort)\n : null}\n </Folder>\n )\n }\n\n return (\n <File\n key={element.id}\n value={element.id}\n isSelectable={element.isSelectable}\n >\n <span>{element.name}</span>\n </File>\n )\n })\n\ntype TreeViewProps = {\n initialSelectedId?: string\n indicator?: boolean\n elements?: TreeViewElement[]\n initialExpandedItems?: string[]\n openIcon?: React.ReactNode\n closeIcon?: React.ReactNode\n sort?: TreeSortMode\n} & Omit<\n React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Root>,\n \"defaultValue\" | \"onValueChange\" | \"type\" | \"value\"\n>\n\nconst Tree = forwardRef<HTMLDivElement, TreeViewProps>(\n (\n {\n className,\n elements,\n initialSelectedId,\n initialExpandedItems,\n children,\n indicator = true,\n openIcon,\n closeIcon,\n sort = \"default\",\n dir,\n ...props\n },\n ref\n ) => {\n const [selectedId, setSelectedId] = useState<string | undefined>(\n initialSelectedId\n )\n const [expandedItems, setExpandedItems] = useState<string[] | undefined>(\n initialExpandedItems\n )\n\n const selectItem = useCallback((id: string) => {\n setSelectedId(id)\n }, [])\n\n const handleExpand = useCallback((id: string) => {\n setExpandedItems((prev) => {\n if (prev?.includes(id)) {\n return prev.filter((item) => item !== id)\n }\n return [...(prev ?? []), id]\n })\n }, [])\n\n const expandSpecificTargetedElements = useCallback(\n (elements?: TreeViewElement[], selectId?: string) => {\n if (!elements || !selectId) return\n const findParent = (\n currentElement: TreeViewElement,\n currentPath: string[] = []\n ) => {\n const isSelectable = currentElement.isSelectable ?? true\n const newPath = [...currentPath, currentElement.id]\n if (currentElement.id === selectId) {\n if (isSelectable) {\n setExpandedItems((prev) => mergeExpandedItems(prev, newPath))\n } else {\n if (newPath.includes(currentElement.id)) {\n newPath.pop()\n setExpandedItems((prev) => mergeExpandedItems(prev, newPath))\n }\n }\n return\n }\n if (\n Array.isArray(currentElement.children) &&\n currentElement.children.length > 0\n ) {\n currentElement.children.forEach((child) => {\n findParent(child, newPath)\n })\n }\n }\n elements.forEach((element) => {\n findParent(element)\n })\n },\n []\n )\n\n useEffect(() => {\n if (initialSelectedId) {\n expandSpecificTargetedElements(elements, initialSelectedId)\n }\n }, [initialSelectedId, elements, expandSpecificTargetedElements])\n\n const direction = dir === \"rtl\" ? \"rtl\" : \"ltr\"\n const treeChildren =\n children ?? (elements ? renderTreeElements(elements, sort) : null)\n\n return (\n <TreeContext.Provider\n value={{\n selectedId,\n expandedItems,\n handleExpand,\n selectItem,\n setExpandedItems,\n indicator,\n openIcon,\n closeIcon,\n direction,\n }}\n >\n <div className={cn(\"size-full\", className)}>\n <ScrollArea\n ref={ref}\n className=\"relative h-full px-2\"\n dir={dir as Direction}\n >\n <AccordionPrimitive.Root\n {...props}\n type=\"multiple\"\n value={expandedItems}\n className=\"flex flex-col gap-1\"\n dir={dir as Direction}\n >\n {treeChildren}\n </AccordionPrimitive.Root>\n </ScrollArea>\n </div>\n </TreeContext.Provider>\n )\n }\n)\n\nTree.displayName = \"Tree\"\n\nconst TreeIndicator = forwardRef<\n HTMLDivElement,\n React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => {\n const { direction } = useTree()\n\n return (\n <div\n dir={direction}\n ref={ref}\n className={cn(\n \"bg-muted absolute left-1.5 h-full w-px rounded-md py-3 duration-300 ease-in-out hover:bg-slate-300 rtl:right-1.5\",\n className\n )}\n {...props}\n />\n )\n})\n\nTreeIndicator.displayName = \"TreeIndicator\"\n\ntype FolderProps = {\n expandedItems?: string[]\n element: string\n isSelectable?: boolean\n isSelect?: boolean\n} & React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>\n\nconst Folder = forwardRef<\n HTMLDivElement,\n FolderProps & React.HTMLAttributes<HTMLDivElement>\n>(\n (\n {\n className,\n element,\n value,\n isSelectable = true,\n isSelect,\n children,\n ...props\n },\n ref\n ) => {\n const {\n direction,\n handleExpand,\n expandedItems,\n indicator,\n selectedId,\n selectItem,\n openIcon,\n closeIcon,\n } = useTree()\n const isSelected = isSelect ?? selectedId === value\n\n return (\n <AccordionPrimitive.Item\n ref={ref}\n {...props}\n value={value}\n className=\"relative h-full overflow-hidden\"\n >\n <AccordionPrimitive.Trigger\n className={cn(\n `flex items-center gap-1 rounded-md text-sm`,\n className,\n {\n \"bg-muted rounded-md\": isSelected && isSelectable,\n \"cursor-pointer\": isSelectable,\n \"cursor-not-allowed opacity-50\": !isSelectable,\n }\n )}\n disabled={!isSelectable}\n onClick={() => {\n selectItem(value)\n handleExpand(value)\n }}\n >\n {expandedItems?.includes(value)\n ? (openIcon ?? <FolderOpenIcon className=\"size-4\" />)\n : (closeIcon ?? <FolderIcon className=\"size-4\" />)}\n <span>{element}</span>\n </AccordionPrimitive.Trigger>\n <AccordionPrimitive.Content className=\"data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down relative h-full overflow-hidden text-sm\">\n {element && indicator && <TreeIndicator aria-hidden=\"true\" />}\n <AccordionPrimitive.Root\n dir={direction}\n type=\"multiple\"\n className=\"ml-5 flex flex-col gap-1 py-1 rtl:mr-5\"\n value={expandedItems}\n >\n {children}\n </AccordionPrimitive.Root>\n </AccordionPrimitive.Content>\n </AccordionPrimitive.Item>\n )\n }\n)\n\nFolder.displayName = \"Folder\"\n\nconst File = forwardRef<\n HTMLButtonElement,\n {\n value: string\n handleSelect?: (id: string) => void\n isSelectable?: boolean\n isSelect?: boolean\n fileIcon?: React.ReactNode\n } & React.ButtonHTMLAttributes<HTMLButtonElement>\n>(\n (\n {\n value,\n className,\n handleSelect,\n onClick,\n isSelectable = true,\n isSelect,\n fileIcon,\n children,\n ...props\n },\n ref\n ) => {\n const { direction, selectedId, selectItem } = useTree()\n const isSelected = isSelect ?? selectedId === value\n return (\n <button\n ref={ref}\n type=\"button\"\n disabled={!isSelectable}\n className={cn(\n \"flex w-fit items-center gap-1 rounded-md pr-1 text-sm duration-200 ease-in-out rtl:pr-0 rtl:pl-1\",\n {\n \"bg-muted\": isSelected && isSelectable,\n },\n isSelectable ? \"cursor-pointer\" : \"cursor-not-allowed opacity-50\",\n direction === \"rtl\" ? \"rtl\" : \"ltr\",\n className\n )}\n onClick={(event) => {\n selectItem(value)\n handleSelect?.(value)\n onClick?.(event)\n }}\n {...props}\n >\n {fileIcon ?? <FileIcon className=\"size-4\" />}\n {children}\n </button>\n )\n }\n)\n\nFile.displayName = \"File\"\n\nconst CollapseButton = forwardRef<\n HTMLButtonElement,\n {\n elements: TreeViewElement[]\n expandAll?: boolean\n } & React.HTMLAttributes<HTMLButtonElement>\n>(({ className, elements, expandAll = false, children, ...props }, ref) => {\n const { expandedItems, setExpandedItems } = useTree()\n\n const expendAllTree = useCallback((elements: TreeViewElement[]) => {\n const expandedElementIds: string[] = []\n\n const expandTree = (element: TreeViewElement) => {\n const isSelectable = element.isSelectable ?? true\n if (isSelectable && element.children && element.children.length > 0) {\n expandedElementIds.push(element.id)\n for (const child of element.children) {\n expandTree(child)\n }\n }\n }\n\n for (const element of elements) {\n expandTree(element)\n }\n\n return [...new Set(expandedElementIds)]\n }, [])\n\n const closeAll = useCallback(() => {\n setExpandedItems?.([])\n }, [setExpandedItems])\n\n useEffect(() => {\n if (expandAll) {\n setExpandedItems?.(expendAllTree(elements))\n }\n }, [expandAll, elements, expendAllTree, setExpandedItems])\n\n return (\n <Button\n variant={\"ghost\"}\n className={cn(\"absolute right-2 bottom-1 h-8 w-fit p-1\", className)}\n onClick={\n expandedItems && expandedItems.length > 0\n ? closeAll\n : () => setExpandedItems?.(expendAllTree(elements))\n }\n ref={ref}\n {...props}\n >\n {children}\n <span className=\"sr-only\">Toggle</span>\n </Button>\n )\n})\n\nCollapseButton.displayName = \"CollapseButton\"\n\nexport { CollapseButton, File, Folder, Tree, type TreeViewElement }\nexport type { TreeSortMode }\n",
"type": "registry:ui"
}
]
diff --git a/apps/www/registry/example/file-tree-demo.tsx b/apps/www/registry/example/file-tree-demo.tsx
index 0fd1cbf0..053a6dfe 100644
--- a/apps/www/registry/example/file-tree-demo.tsx
+++ b/apps/www/registry/example/file-tree-demo.tsx
@@ -1,108 +1,85 @@
-import { File, Folder, Tree } from "@/registry/magicui/file-tree"
+import { Tree } from "@/registry/magicui/file-tree"
+import type { TreeViewElement } from "@/registry/magicui/file-tree"
export default function FileTreeDemo() {
return (
- <div className="bg-background relative flex h-[300px] w-1/2 flex-col items-center justify-center overflow-hidden rounded-lg border">
+ <div className="bg-background relative flex h-[300px] w-full max-w-sm flex-col items-center justify-center overflow-hidden rounded-lg border">
<Tree
className="bg-background overflow-hidden rounded-md p-2"
- initialSelectedId="7"
- initialExpandedItems={[
- "1",
- "2",
- "3",
- "4",
- "5",
- "6",
- "7",
- "8",
- "9",
- "10",
- "11",
- ]}
+ initialSelectedId="button"
+ initialExpandedItems={["src", "app", "components", "ui", "lib"]}
elements={ELEMENTS}
- >
- <Folder element="src" value="1">
- <Folder value="2" element="app">
- <File value="3">
- <p>layout.tsx</p>
- </File>
- <File value="4">
- <p>page.tsx</p>
- </File>
- </Folder>
- <Folder value="5" element="components">
- <Folder value="6" element="ui">
- <File value="7">
- <p>button.tsx</p>
- </File>
- </Folder>
- <File value="8">
- <p>header.tsx</p>
- </File>
- <File value="9">
- <p>footer.tsx</p>
- </File>
- </Folder>
- <Folder value="10" element="lib">
- <File value="11">
- <p>utils.ts</p>
- </File>
- </Folder>
- </Folder>
- </Tree>
+ />
</div>
)
}
-const ELEMENTS = [
+const ELEMENTS: TreeViewElement[] = [
{
- id: "1",
+ id: "src",
+ type: "folder",
isSelectable: true,
name: "src",
children: [
{
- id: "2",
+ id: "lib",
+ type: "folder",
isSelectable: true,
- name: "app",
+ name: "lib",
children: [
{
- id: "3",
+ id: "utils",
isSelectable: true,
- name: "layout.tsx",
+ name: "utils.ts",
},
+ ],
+ },
+ {
+ id: "app",
+ type: "folder",
+ isSelectable: true,
+ name: "app",
+ children: [
{
- id: "4",
+ id: "page",
isSelectable: true,
name: "page.tsx",
},
+ {
+ id: "layout",
+ isSelectable: true,
+ name: "layout.tsx",
+ },
],
},
{
- id: "5",
+ id: "components",
+ type: "folder",
isSelectable: true,
name: "components",
children: [
{
- id: "6",
+ id: "header",
isSelectable: true,
name: "header.tsx",
},
{
- id: "7",
+ id: "ui",
+ type: "folder",
isSelectable: true,
- name: "footer.tsx",
+ name: "ui",
+ children: [
+ {
+ id: "button",
+ isSelectable: true,
+ name: "button.tsx",
+ },
+ ],
},
- ],
- },
- {
- id: "8",
- isSelectable: true,
- name: "lib",
- children: [
{
- id: "9",
+ id: "footer",
isSelectable: true,
- name: "utils.ts",
+ name: "footer.tsx",
},
],
},
diff --git a/apps/www/registry/magicui/file-tree.tsx b/apps/www/registry/magicui/file-tree.tsx
index 14de368e..d448296e 100644
--- a/apps/www/registry/magicui/file-tree.tsx
+++ b/apps/www/registry/magicui/file-tree.tsx
@@ -18,10 +18,16 @@ import { ScrollArea } from "@/components/ui/scroll-area"
type TreeViewElement = {
id: string
name: string
+ type?: "file" | "folder"
isSelectable?: boolean
children?: TreeViewElement[]
}
+type TreeSortMode =
+ | "default"
+ | "none"
+ | ((a: TreeViewElement, b: TreeViewElement) => number)
+
type TreeContextProps = {
selectedId: string | undefined
expandedItems: string[] | undefined
@@ -46,6 +52,102 @@ const useTree = () => {
type Direction = "rtl" | "ltr" | undefined
+const isFolderElement = (element: TreeViewElement) => {
+ if (element.type) {
+ return element.type === "folder"
+ }
+
+ return Array.isArray(element.children)
+}
+
+const mergeExpandedItems = (
+ currentItems: string[] | undefined,
+ nextItems: string[]
+) => [...new Set([...(currentItems ?? []), ...nextItems])]
+
+const treeCollator = new Intl.Collator("en", {
+ numeric: true,
+ sensitivity: "base",
+})
+
+const defaultTreeComparator = (a: TreeViewElement, b: TreeViewElement) => {
+ const aIsFolder = isFolderElement(a)
+ const bIsFolder = isFolderElement(b)
+
+ if (aIsFolder !== bIsFolder) {
+ return aIsFolder ? -1 : 1
+ }
+
+ return treeCollator.compare(a.name, b.name)
+}
+
+const getTreeComparator = (sort: TreeSortMode) => {
+ if (sort === "none") {
+ return undefined
+ }
+
+ if (sort === "default") {
+ return defaultTreeComparator
+ }
+
+ return sort
+}
+
+const sortTreeElements = (
+ elements: TreeViewElement[],
+ sort: TreeSortMode
+): TreeViewElement[] => {
+ const comparator = getTreeComparator(sort)
+
+ const nextElements = elements.map((element) => {
+ if (!Array.isArray(element.children)) {
+ return element
+ }
+
+ return {
+ ...element,
+ children: sortTreeElements(element.children, sort),
+ }
+ })
+
+ if (!comparator) {
+ return nextElements
+ }
+
+ return [...nextElements].sort(comparator)
+}
+
+const renderTreeElements = (
+ elements: TreeViewElement[],
+ sort: TreeSortMode
+): React.ReactNode =>
+ sortTreeElements(elements, sort).map((element) => {
+ if (isFolderElement(element)) {
+ return (
+ <Folder
+ key={element.id}
+ value={element.id}
+ element={element.name}
+ isSelectable={element.isSelectable}
+ >
+ {Array.isArray(element.children)
+ ? renderTreeElements(element.children, sort)
+ : null}
+ </Folder>
+ )
+ }
+
+ return (
+ <File
+ key={element.id}
+ value={element.id}
+ isSelectable={element.isSelectable}
+ >
+ <span>{element.name}</span>
+ </File>
+ )
+ })
+
type TreeViewProps = {
initialSelectedId?: string
indicator?: boolean
@@ -53,7 +155,11 @@ type TreeViewProps = {
initialExpandedItems?: string[]
openIcon?: React.ReactNode
closeIcon?: React.ReactNode
-} & React.HTMLAttributes<HTMLDivElement>
+ sort?: TreeSortMode
+} & Omit<
+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Root>,
+ "defaultValue" | "onValueChange" | "type" | "value"
+>
const Tree = forwardRef<HTMLDivElement, TreeViewProps>(
(
@@ -66,6 +172,7 @@ const Tree = forwardRef<HTMLDivElement, TreeViewProps>(
indicator = true,
openIcon,
closeIcon,
+ sort = "default",
dir,
...props
},
@@ -102,18 +209,17 @@ const Tree = forwardRef<HTMLDivElement, TreeViewProps>(
const newPath = [...currentPath, currentElement.id]
if (currentElement.id === selectId) {
if (isSelectable) {
- setExpandedItems((prev) => [...(prev ?? []), ...newPath])
+ setExpandedItems((prev) => mergeExpandedItems(prev, newPath))
} else {
if (newPath.includes(currentElement.id)) {
newPath.pop()
- setExpandedItems((prev) => [...(prev ?? []), ...newPath])
+ setExpandedItems((prev) => mergeExpandedItems(prev, newPath))
}
}
return
}
if (
- isSelectable &&
- currentElement.children &&
+ Array.isArray(currentElement.children) &&
currentElement.children.length > 0
) {
currentElement.children.forEach((child) => {
@@ -135,6 +241,8 @@ const Tree = forwardRef<HTMLDivElement, TreeViewProps>(
}, [initialSelectedId, elements, expandSpecificTargetedElements])
const direction = dir === "rtl" ? "rtl" : "ltr"
+ const treeChildren =
+ children ?? (elements ? renderTreeElements(elements, sort) : null)
return (
<TreeContext.Provider
@@ -159,15 +267,11 @@ const Tree = forwardRef<HTMLDivElement, TreeViewProps>(
<AccordionPrimitive.Root
{...props}
type="multiple"
- defaultValue={expandedItems}
value={expandedItems}
className="flex flex-col gap-1"
- onValueChange={(value) =>
- setExpandedItems((prev) => [...(prev ?? []), value[0]])
- }
dir={dir as Direction}
>
- {children}
+ {treeChildren}
</AccordionPrimitive.Root>
</ScrollArea>
</div>
@@ -227,10 +331,12 @@ const Folder = forwardRef<
handleExpand,
expandedItems,
indicator,
- setExpandedItems,
+ selectedId,
+ selectItem,
openIcon,
closeIcon,
} = useTree()
+ const isSelected = isSelect ?? selectedId === value
return (
<AccordionPrimitive.Item
@@ -244,13 +350,16 @@ const Folder = forwardRef<
`flex items-center gap-1 rounded-md text-sm`,
className,
{
- "bg-muted rounded-md": isSelect && isSelectable,
+ "bg-muted rounded-md": isSelected && isSelectable,
"cursor-pointer": isSelectable,
"cursor-not-allowed opacity-50": !isSelectable,
}
)}
disabled={!isSelectable}
- onClick={() => handleExpand(value)}
+ onClick={() => {
+ selectItem(value)
+ handleExpand(value)
+ }}
>
{expandedItems?.includes(value)
? (openIcon ?? <FolderOpenIcon className="size-4" />)
@@ -263,11 +372,7 @@ const Folder = forwardRef<
dir={direction}
type="multiple"
className="ml-5 flex flex-col gap-1 py-1 rtl:mr-5"
- defaultValue={expandedItems}
value={expandedItems}
- onValueChange={(value) => {
- setExpandedItems?.((prev) => [...(prev ?? []), value[0]])
- }}
>
{children}
</AccordionPrimitive.Root>
@@ -395,3 +500,4 @@ const CollapseButton = forwardRef<
CollapseButton.displayName = "CollapseButton"
export { CollapseButton, File, Folder, Tree, type TreeViewElement }
+export type { TreeSortMode }