# File Tree

> A nested list of folders and files for browsing and previewing project files.

```tsx title="hero.tsx"
import type { FileTreeIconType } from '@langgenius/dify-ui/file-tree'
import {
  FileTree,
  FileTreeFile,
  FileTreeFolder,
  FileTreeFolderPanel,
  FileTreeFolderTrigger,
  FileTreeIcon,
  FileTreeLabel,
  FileTreeList,
} from '@langgenius/dify-ui/file-tree'
import * as React from 'react'

type PluginFile = {
  path: string
  name: string
  icon: FileTreeIconType
  meta: string
  preview: string
}

const providerFiles: PluginFile[] = [
  {
    path: 'provider/weather.yaml',
    name: 'weather.yaml',
    icon: 'code',
    meta: 'YAML · 6 lines',
    preview: `identity:
  author: langgenius
  name: weather
credentials_for_provider:
  api_key:
    type: secret-input`,
  },
  {
    path: 'provider/weather.py',
    name: 'weather.py',
    icon: 'code',
    meta: 'Python · 5 lines',
    preview: `class WeatherProvider(ToolProvider):
    def _validate_credentials(self, credentials):
        if not credentials.get("api_key"):
            raise ToolProviderCredentialValidationError("Missing key")`,
  },
]

const toolFiles: PluginFile[] = [
  {
    path: 'tools/current_weather.yaml',
    name: 'current_weather.yaml',
    icon: 'code',
    meta: 'YAML · 7 lines',
    preview: `identity:
  name: current_weather
parameters:
  - name: city
    type: string
    required: true
    form: llm`,
  },
  {
    path: 'tools/current_weather.py',
    name: 'current_weather.py',
    icon: 'code',
    meta: 'Python · 5 lines',
    preview: `class CurrentWeatherTool(Tool):
    def _invoke(self, tool_parameters):
        city = tool_parameters["city"]
        return self.create_json_message(fetch_current(city))`,
  },
  {
    path: 'tools/forecast.yaml',
    name: 'forecast.yaml',
    icon: 'code',
    meta: 'YAML · 8 lines',
    preview: `identity:
  name: forecast
parameters:
  - name: city
    type: string
    required: true
  - name: days
    type: number`,
  },
  {
    path: 'tools/forecast.py',
    name: 'forecast.py',
    icon: 'code',
    meta: 'Python · 5 lines',
    preview: `class ForecastTool(Tool):
    def _invoke(self, tool_parameters):
        days = int(tool_parameters.get("days", 3))
        return self.create_json_message(fetch_forecast(days))`,
  },
]

const assetFile: PluginFile = {
  path: '_assets/icon.svg',
  name: 'icon.svg',
  icon: 'image',
  meta: 'SVG · 412 B',
  preview: `<svg viewBox="0 0 24 24" fill="none">
  <circle cx="12" cy="12" r="5" />
  <path d="M12 2v3m0 14v3M2 12h3m14 0h3" />
</svg>`,
}

const rootFiles: PluginFile[] = [
  {
    path: 'manifest.yaml',
    name: 'manifest.yaml',
    icon: 'code',
    meta: 'YAML · 6 lines',
    preview: `version: 0.4.2
type: plugin
author: langgenius
name: weather
plugins:
  tools: [provider/weather.yaml]`,
  },
  {
    path: 'main.py',
    name: 'main.py',
    icon: 'code',
    meta: 'Python · 4 lines',
    preview: `from dify_plugin import Plugin, DifyPluginEnv

plugin = Plugin(DifyPluginEnv())
plugin.run()`,
  },
  {
    path: 'requirements.txt',
    name: 'requirements.txt',
    icon: 'text',
    meta: 'Text · 2 lines',
    preview: `dify_plugin>=0.2.0,<0.3.0
httpx>=0.27.0`,
  },
  {
    path: 'README.md',
    name: 'README.md',
    icon: 'markdown',
    meta: 'Markdown · 4 lines',
    preview: `# Weather plugin

Fetch live weather conditions and multi-day
forecasts inside Dify workflows and agents.`,
  },
  {
    path: 'PRIVACY.md',
    name: 'PRIVACY.md',
    icon: 'markdown',
    meta: 'Markdown · 3 lines',
    preview: `# Privacy policy

City names are forwarded to the configured
weather API and are not stored by the plugin.`,
  },
]

const filesByPath = new Map(
  [assetFile, ...providerFiles, ...toolFiles, ...rootFiles].map((file) => [file.path, file]),
)

export function FileTreeHeroDemo() {
  const [selectedPath, setSelectedPath] = React.useState('tools/forecast.yaml')
  const selectedFile = filesByPath.get(selectedPath)

  const renderFile = ({ path, name, icon }: PluginFile) => (
    <FileTreeFile key={path} selected={selectedPath === path} onClick={() => setSelectedPath(path)}>
      <FileTreeIcon type={icon} />
      <FileTreeLabel>{name}</FileTreeLabel>
    </FileTreeFile>
  )

  return (
    <div className="flex w-full max-w-xl flex-col overflow-hidden rounded-xl border border-divider-subtle sm:flex-row">
      <FileTree
        aria-label="Weather plugin files"
        className="shrink-0 border-b border-divider-subtle bg-background-default-subtle sm:w-52 sm:border-e sm:border-b-0"
      >
        <FileTreeList>
          <FileTreeFolder>
            <FileTreeFolderTrigger>
              <FileTreeIcon type="folder" />
              <FileTreeLabel>_assets</FileTreeLabel>
            </FileTreeFolderTrigger>
            <FileTreeFolderPanel>{renderFile(assetFile)}</FileTreeFolderPanel>
          </FileTreeFolder>
          <FileTreeFolder>
            <FileTreeFolderTrigger>
              <FileTreeIcon type="folder" />
              <FileTreeLabel>provider</FileTreeLabel>
            </FileTreeFolderTrigger>
            <FileTreeFolderPanel>{providerFiles.map(renderFile)}</FileTreeFolderPanel>
          </FileTreeFolder>
          <FileTreeFolder defaultOpen>
            <FileTreeFolderTrigger>
              <FileTreeIcon type="folder" />
              <FileTreeLabel>tools</FileTreeLabel>
            </FileTreeFolderTrigger>
            <FileTreeFolderPanel>{toolFiles.map(renderFile)}</FileTreeFolderPanel>
          </FileTreeFolder>
          {rootFiles.map(renderFile)}
        </FileTreeList>
      </FileTree>
      <div className="flex min-w-0 flex-1 flex-col bg-background-default">
        <div className="flex items-center justify-between gap-2 border-b border-divider-subtle px-4 py-2.5">
          <span className="truncate font-mono system-xs-medium text-text-primary">
            {selectedFile?.path}
          </span>
          <span className="shrink-0 system-xs-regular text-text-tertiary">
            {selectedFile?.meta}
          </span>
        </div>
        <pre className="m-0 flex-1 overflow-x-auto p-4 code-xs-regular text-text-secondary">
          <code>{selectedFile?.preview}</code>
        </pre>
      </div>
    </div>
  )
}
```

## Usage guidelines

- **Use it to browse and preview files**: Folders are disclosure buttons and files are buttons. The feature owns data loading, routing, renaming, drag and drop and per-item actions.
- **It is not an ARIA tree**: `FileTree` renders a labelled `<section>` of nested lists, not `role="tree"`. Every row is a separate tab stop, and arrow keys, `Home`, `End` and typeahead do not move between rows. Keep trees short enough to tab through, or add a search or filter next to large ones.
- **Name the tree**: Give `FileTree` an `aria-label` or `aria-labelledby` that says what the files belong to, such as "Weather plugin files".
- **Mark the open file with `selected`**: `selected` sets `aria-current="true"` and the highlighted row style. Keep one selected file, driven by the feature's state or route.
- **A file click previews, it does not navigate**: `FileTreeFile` renders a `<button>`. Handle `onClick` to open the preview; do not render a link through it.
- **Use `disabled` for entries that cannot be opened**: A disabled folder keeps its open state but cannot be toggled, and a disabled file leaves the tab order.
- **Let the context set the indent**: Nesting `FileTreeFolderPanel` raises the level and draws one guide per level. Pass `level` only when rendering a row outside its folder, such as a virtualized flat list.

## Anatomy

```tsx
import {
  FileTree,
  FileTreeBadge,
  FileTreeFile,
  FileTreeFolder,
  FileTreeFolderPanel,
  FileTreeFolderTrigger,
  FileTreeIcon,
  FileTreeLabel,
  FileTreeList,
  FileTreeMeta,
} from '@langgenius/dify-ui/file-tree'
```

```tsx
<FileTree>
  <FileTreeList>
    <FileTreeFolder>
      <FileTreeFolderTrigger>
        <FileTreeIcon type="folder" />
        <FileTreeLabel />
      </FileTreeFolderTrigger>
      <FileTreeFolderPanel>
        <FileTreeFile>
          <FileTreeIcon />
          <FileTreeLabel />
          <FileTreeMeta />
          <FileTreeBadge />
        </FileTreeFile>
      </FileTreeFolderPanel>
    </FileTreeFolder>
  </FileTreeList>
</FileTree>
```

`FileTreeFolder` is a Base UI Collapsible root rendered as `<li>`; `FileTreeFile` wraps its button in an `<li>`. `FileTreeIcon` is decorative, so the row's name comes from `FileTreeLabel` and any meta or badge text. Rows render one `FileTreeGuide` per nesting level themselves; render it directly only in a custom row.

## Examples

### Rendering from data

Render folders and files recursively from the feature's data. `FileTreeMeta` adds a short status after the label and `FileTreeBadge` a compact value such as a size. Both become part of the row's accessible name.

```tsx title="data-driven.tsx"
import type { FileTreeIconType } from '@langgenius/dify-ui/file-tree'
import {
  FileTree,
  FileTreeBadge,
  FileTreeFile,
  FileTreeFolder,
  FileTreeFolderPanel,
  FileTreeFolderTrigger,
  FileTreeIcon,
  FileTreeLabel,
  FileTreeList,
  FileTreeMeta,
} from '@langgenius/dify-ui/file-tree'
import * as React from 'react'

type DocumentNode = {
  id: string
  name: string
  icon: FileTreeIconType
  meta?: string
  badge?: string
  children?: DocumentNode[]
}

const documents: DocumentNode[] = [
  {
    id: 'product',
    name: 'product-docs',
    icon: 'folder',
    children: [
      { id: 'getting-started', name: 'getting-started.md', icon: 'markdown' },
      { id: 'api-reference', name: 'api-reference.pdf', icon: 'pdf', badge: '12 MB' },
      {
        id: 'guides',
        name: 'guides',
        icon: 'folder',
        children: [
          { id: 'rag-pipeline', name: 'rag-pipeline.md', icon: 'markdown' },
          {
            id: 'agent-strategies',
            name: 'agent-strategies.md',
            icon: 'markdown',
            meta: 'indexing',
          },
        ],
      },
    ],
  },
  {
    id: 'support',
    name: 'support',
    icon: 'folder',
    children: [
      { id: 'faq', name: 'faq.csv', icon: 'table' },
      { id: 'pricing', name: 'pricing.xlsx', icon: 'table' },
    ],
  },
  { id: 'changelog', name: 'changelog.txt', icon: 'text' },
  { id: 'export', name: 'workspace-export.zip', icon: 'archive', badge: '48 MB' },
]

export function FileTreeDataDrivenDemo() {
  const [selectedId, setSelectedId] = React.useState('getting-started')

  const renderNodes = (nodes: DocumentNode[]) =>
    nodes.map((node) =>
      node.children ? (
        <FileTreeFolder key={node.id} defaultOpen={node.id !== 'support'}>
          <FileTreeFolderTrigger>
            <FileTreeIcon type={node.icon} />
            <FileTreeLabel>{node.name}</FileTreeLabel>
          </FileTreeFolderTrigger>
          <FileTreeFolderPanel>{renderNodes(node.children)}</FileTreeFolderPanel>
        </FileTreeFolder>
      ) : (
        <FileTreeFile
          key={node.id}
          selected={selectedId === node.id}
          onClick={() => setSelectedId(node.id)}
        >
          <FileTreeIcon type={node.icon} />
          <FileTreeLabel>{node.name}</FileTreeLabel>
          {node.meta && <FileTreeMeta>{node.meta}</FileTreeMeta>}
          {node.badge && <FileTreeBadge>{node.badge}</FileTreeBadge>}
        </FileTreeFile>
      ),
    )

  return (
    <FileTree aria-label="Product knowledge base documents" className="w-full max-w-80">
      <FileTreeList>{renderNodes(documents)}</FileTreeList>
    </FileTree>
  )
}
```

### Controlled folders

Pass `open` and `onOpenChange` to `FileTreeFolder` when something outside the tree opens folders, such as an expand-all action or revealing the file that is open in the editor.

```tsx title="controlled.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
  FileTree,
  FileTreeFile,
  FileTreeFolder,
  FileTreeFolderPanel,
  FileTreeFolderTrigger,
  FileTreeIcon,
  FileTreeLabel,
  FileTreeList,
} from '@langgenius/dify-ui/file-tree'
import * as React from 'react'

const folders = [
  { name: 'nodes', files: ['llm.json', 'knowledge-retrieval.json', 'code.json'] },
  { name: 'variables', files: ['environment.json', 'conversation.json'] },
]

export function FileTreeControlledDemo() {
  const [openFolders, setOpenFolders] = React.useState<string[]>(['nodes'])
  const [selectedFile, setSelectedFile] = React.useState('nodes/llm.json')
  const allOpen = openFolders.length === folders.length
  const titleId = React.useId()

  return (
    <div className="flex w-full max-w-80 flex-col gap-1">
      <div className="flex items-center justify-between border-b border-divider-subtle ps-2 pb-1.5">
        <p id={titleId} className="m-0 system-xs-semibold-uppercase text-text-tertiary">
          Workflow files
        </p>
        <Button
          size="small"
          variant="ghost"
          onClick={() => setOpenFolders(allOpen ? [] : folders.map(({ name }) => name))}
        >
          {allOpen ? 'Collapse all' : 'Expand all'}
        </Button>
      </div>
      <FileTree aria-labelledby={titleId} className="p-0">
        <FileTreeList>
          {folders.map(({ name, files }) => (
            <FileTreeFolder
              key={name}
              open={openFolders.includes(name)}
              onOpenChange={(open) =>
                setOpenFolders((current) =>
                  open ? [...current, name] : current.filter((folder) => folder !== name),
                )
              }
            >
              <FileTreeFolderTrigger>
                <FileTreeIcon type="folder" />
                <FileTreeLabel>{name}</FileTreeLabel>
              </FileTreeFolderTrigger>
              <FileTreeFolderPanel>
                {files.map((file) => {
                  const path = `${name}/${file}`
                  return (
                    <FileTreeFile
                      key={path}
                      selected={selectedFile === path}
                      onClick={() => setSelectedFile(path)}
                    >
                      <FileTreeIcon type="json" />
                      <FileTreeLabel>{file}</FileTreeLabel>
                    </FileTreeFile>
                  )
                })}
              </FileTreeFolderPanel>
            </FileTreeFolder>
          ))}
          <FileTreeFile
            selected={selectedFile === 'workflow.yml'}
            onClick={() => setSelectedFile('workflow.yml')}
          >
            <FileTreeIcon type="code" />
            <FileTreeLabel>workflow.yml</FileTreeLabel>
          </FileTreeFile>
        </FileTreeList>
      </FileTree>
    </div>
  )
}
```

### Disabled entries

A disabled folder keeps its current open or closed state and cannot be toggled, while a disabled file cannot be opened. Explain why with `FileTreeMeta` when the reason is not obvious.

```tsx title="disabled.tsx"
import {
  FileTree,
  FileTreeFile,
  FileTreeFolder,
  FileTreeFolderPanel,
  FileTreeFolderTrigger,
  FileTreeIcon,
  FileTreeLabel,
  FileTreeList,
  FileTreeMeta,
} from '@langgenius/dify-ui/file-tree'
import * as React from 'react'

export function FileTreeDisabledDemo() {
  const [selectedFile, setSelectedFile] = React.useState('manifest.yaml')

  return (
    <FileTree aria-label="Installed plugin files" className="w-full max-w-80">
      <FileTreeList>
        <FileTreeFolder disabled>
          <FileTreeFolderTrigger>
            <FileTreeIcon type="folder" />
            <FileTreeLabel>.venv</FileTreeLabel>
            <FileTreeMeta>generated</FileTreeMeta>
          </FileTreeFolderTrigger>
          <FileTreeFolderPanel />
        </FileTreeFolder>
        <FileTreeFolder defaultOpen disabled>
          <FileTreeFolderTrigger>
            <FileTreeIcon type="folder" />
            <FileTreeLabel>schemas</FileTreeLabel>
            <FileTreeMeta>locked open</FileTreeMeta>
          </FileTreeFolderTrigger>
          <FileTreeFolderPanel>
            <FileTreeFile
              selected={selectedFile === 'schemas/input.json'}
              onClick={() => setSelectedFile('schemas/input.json')}
            >
              <FileTreeIcon type="json" />
              <FileTreeLabel>input.json</FileTreeLabel>
            </FileTreeFile>
          </FileTreeFolderPanel>
        </FileTreeFolder>
        <FileTreeFile
          selected={selectedFile === 'manifest.yaml'}
          onClick={() => setSelectedFile('manifest.yaml')}
        >
          <FileTreeIcon type="code" />
          <FileTreeLabel>manifest.yaml</FileTreeLabel>
        </FileTreeFile>
        <FileTreeFile disabled>
          <FileTreeIcon type="file" />
          <FileTreeLabel>.env</FileTreeLabel>
          <FileTreeMeta>hidden</FileTreeMeta>
        </FileTreeFile>
      </FileTreeList>
    </FileTree>
  )
}
```

## Keyboard

| Key              | Action                                                                                  |
| ---------------- | --------------------------------------------------------------------------------------- |
| `Tab`            | Moves focus to the next visible folder or file. Disabled folders and files are skipped. |
| `Shift` + `Tab`  | Moves focus to the previous visible folder or file.                                     |
| `Enter`, `Space` | On a folder, expands or collapses it. On a file, activates it.                          |

## API reference

### FileTree

A composable hierarchical file list built with Base UI Collapsible. Renders a `<section>` element.

Folders are disclosure buttons and files are preview buttons; feature code owns data loading, routing, and item actions.

Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).

### FileTreeBadge

Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).

### FileTreeFile

**Props**

| Prop        | Type      | Default | Description                                                                                                                         |
| ----------- | --------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `level?`    | `number`  | —       | The nesting depth of the row, starting at 1, which sets its indentation guides. Inferred from the surrounding folders when omitted. |
| `selected?` | `boolean` | `false` | Whether the file is the currently selected one, marked with `aria-current`.                                                         |

Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).

**Data attributes**

| Attribute       | Description                                |
| --------------- | ------------------------------------------ |
| `data-selected` | Present when the file is the selected row. |
| `data-disabled` | Present when the file is disabled.         |

### FileTreeFolder

Groups all parts of the collapsible. Renders a `<div>` element.

Inherits `className`, `open`, `defaultOpen`, `onOpenChange`, `disabled`, `render`, `style` from [Base UI Collapsible.Root](https://base-ui.com/react/components/collapsible#root).

**Data attributes**

| Attribute             | Description                                       |
| --------------------- | ------------------------------------------------- |
| `data-open`           | Present when the collapsible is open.             |
| `data-closed`         | Present when the collapsible is closed.           |
| `data-starting-style` | Present when the collapsible begins animating in. |
| `data-ending-style`   | Present when the collapsible is animating out.    |

### FileTreeFolderPanel

A panel with the collapsible contents. Renders a `<div>` element.

Inherits `hiddenUntilFound`, `keepMounted`, `className`, `render`, `style` from [Base UI Collapsible.Panel](https://base-ui.com/react/components/collapsible#panel).

**Data attributes**

| Attribute             | Description                                   |
| --------------------- | --------------------------------------------- |
| `data-open`           | Present when the collapsible panel is open.   |
| `data-closed`         | Present when the collapsible panel is closed. |
| `data-starting-style` | Present when the panel begins animating in.   |
| `data-ending-style`   | Present when the panel is animating out.      |

**CSS variables**

| Variable                     | Type     | Description                     |
| ---------------------------- | -------- | ------------------------------- |
| `--collapsible-panel-height` | `number` | The collapsible panel's height. |
| `--collapsible-panel-width`  | `number` | The collapsible panel's width.  |

### FileTreeFolderTrigger

A button that opens and closes the collapsible panel. Renders a `<button>` element.

**Props**

| Prop     | Type     | Default | Description                                                                                                                         |
| -------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `level?` | `number` | —       | The nesting depth of the row, starting at 1, which sets its indentation guides. Inferred from the surrounding folders when omitted. |

Inherits `className`, `render`, `style`, `nativeButton` from [Base UI Collapsible.Trigger](https://base-ui.com/react/components/collapsible#trigger).

**Data attributes**

| Attribute         | Description                                 |
| ----------------- | ------------------------------------------- |
| `data-panel-open` | Present when the collapsible panel is open. |

### FileTreeGuide

Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).

### FileTreeIcon

**Props**

| Prop        | Type                                                                                                                       | Default  | Description                                                                                                          |
| ----------- | -------------------------------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------- |
| `type?`     | `'archive' \| 'code' \| 'database' \| 'file' \| 'folder' \| 'image' \| 'json' \| 'markdown' \| 'pdf' \| 'table' \| 'text'` | `'file'` | The kind of file the icon represents. `'folder'` switches between closed and open icons with the surrounding folder. |
| `children?` | `React.ReactNode`                                                                                                          | —        | A custom icon that replaces the one chosen by `type`.                                                                |

Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).

### FileTreeLabel

Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).

### FileTreeList

Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).

### FileTreeMeta

Inherits `render` from [Base UI null](https://base-ui.com/react/handbook/composition).
