# Tree

浏览文件、页面或选项的层级，分支可以展开。

当条目有子节点时使用 Tree，比如文件夹里的文件，或文档侧边栏里的页面。先写嵌套的部件，再按需添加选择、复选框，或从服务器加载的子节点。

```svelte title="demo.svelte"
<script lang="ts">
  import {
    ChevronRightIcon,
    FileIcon,
    FolderIcon,
    FolderOpenIcon,
  } from "@lucide/svelte"
  import {
    Tree,
    TreeGroup,
    TreeItem,
    TreeItemIndicator,
    TreeItemLabel,
  } from "@ui-sdk/svelte/tree"

  type Node = { value: string; label: string; children?: Node[] }

  const files: Node[] = [
    {
      value: "app",
      label: "app",
      children: [
        { value: "app/layout.tsx", label: "layout.tsx" },
        { value: "app/page.tsx", label: "page.tsx" },
        {
          value: "app/settings",
          label: "settings",
          children: [{ value: "app/settings/page.tsx", label: "page.tsx" }],
        },
      ],
    },
    {
      value: "components",
      label: "components",
      children: [
        { value: "components/button.tsx", label: "button.tsx" },
        { value: "components/card.tsx", label: "card.tsx" },
      ],
    },
    { value: "components.json", label: "components.json" },
    { value: "package.json", label: "package.json" },
    { value: "README.md", label: "README.md" },
  ]
</script>

{#snippet items(nodes: Node[])}
  {#each nodes as item (item.value)}
    <TreeItem value={item.value}>
      <TreeItemLabel>
        {#if item.children}
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
          <FolderIcon aria-hidden="true" />
          <FolderOpenIcon aria-hidden="true" />
        {:else}
          <FileIcon aria-hidden="true" />
        {/if}
        <span>{item.label}</span>
      </TreeItemLabel>
      {#if item.children}
        <TreeGroup>
          {@render items(item.children)}
        </TreeGroup>
      {/if}
    </TreeItem>
  {/each}
{/snippet}

<Tree aria-label="Files" defaultExpanded={["app"]} defaultValue="app/page.tsx">
  {@render items(files)}
</Tree>
```

展开 components 查看它的文件。用方向键在各行之间移动，并展开或折叠分支。

## 安装
```bash
npm install @ui-sdk/svelte @ui-sdk/core
```

## 组合
用下面的组合构建 `Tree`：

```text
Tree
├── TreeItem
│   ├── TreeItemLabel
│   │   └── TreeItemIndicator
│   └── TreeGroup
│       └── TreeItem
│           └── TreeItemLabel
└── TreeItem
    └── TreeItemLabel
```

给树一个无障碍名称，并给每个条目一个唯一的 `value`。内部包含 `TreeGroup` 的条目是分支。分组容纳它的子节点；标签为条目提供名称。指示器和复选框是可选的，它们属于外面的条目，所以放进条目的标签里，让它们成为这一行的一部分。

## 用法
导入部件并把它们组合起来：

```svelte
<script lang="ts">
  import {
    Tree,
    TreeGroup,
    TreeItem,
    TreeItemIndicator,
    TreeItemLabel,
  } from "@ui-sdk/svelte/tree"
</script>

<Tree aria-label="Project files">
  <TreeItem value="src">
    <TreeItemLabel>
      <TreeItemIndicator>›</TreeItemIndicator>
      src
    </TreeItemLabel>
    <TreeGroup>
      <TreeItem value="src/index.ts">
        <TreeItemLabel>index.ts</TreeItemLabel>
      </TreeItem>
    </TreeGroup>
  </TreeItem>
  <TreeItem value="package.json">
    <TreeItemLabel>package.json</TreeItemLabel>
  </TreeItem>
</Tree>
```

## 以数据形式提供的条目
传入 `items`，给树完整的层级，包括折叠的分支。每个 `TreeItemData` 有一个 `value`、一个 `label`，以及可选的 `children`。树自己没有子节点时，会用数据渲染不带内容的部件：

```svelte
<script lang="ts">
  const items: TreeItemData[] = [
    {
      value: "fruit",
      label: "Fruit",
      children: [
        { value: "apple", label: "Apple" },
        { value: "banana", label: "Banana" },
      ],
    },
    { value: "bread", label: "Bread" },
  ]
</script>

<Tree aria-label="Groceries" {items} />
```

要自己渲染各行，就把 `items` 留在树上，用递归 snippet 渲染它们，这样键盘导航、条目计数和控制器仍然知道整个层级：

```svelte
{#snippet treeItems(nodes: TreeItemData[])}
  {#each nodes as item (item.value)}
    <TreeItem value={item.value}>
      <TreeItemLabel>{item.label}</TreeItemLabel>
      {#if item.children}
        <TreeGroup>
          {@render treeItems(item.children)}
        </TreeGroup>
      {/if}
    </TreeItem>
  {/each}
{/snippet}

<Tree aria-label="Groceries" {items}>
  {@render treeItems(items)}
</Tree>
```

## 文件路径
传入 `paths` 得到一个文件浏览器。文件夹会成为分支，并排在文件前面；以 `/` 结尾的路径表示空文件夹。想自己渲染各行时，`treeFromPaths()` 返回同样的数据。

选择和激活是分开的。这个示例设置 `activation="automatic"`，方向键会选中文件，然后由 `onAction` 打开它。在动作回调里返回 promise，打开期间就会显示待处理状态。

```svelte title="paths.svelte"
<script lang="ts">
  import { ChevronRightIcon, LoaderCircleIcon } from "@lucide/svelte"
  import {
    Tree,
    TreeGroup,
    TreeItem,
    TreeItemIndicator,
    TreeItemLabel,
    treeFromPaths,
    type TreeItemData,
  } from "@ui-sdk/svelte/tree"
  import { useLog } from "./log"

  const paths = [
    "src/index.ts",
    "src/lib/format.ts",
    "src/lib/parse.ts",
    "src/routes/home.tsx",
    "src/routes/about.tsx",
    "tests/",
    "package.json",
    "tsconfig.json",
  ]

  const items = treeFromPaths(paths)
  const files = new Set(paths.filter((path) => !path.endsWith("/")))

  const log = useLog()

  async function onAction(value: string) {
    if (!files.has(value)) {
      return
    }
    await new Promise((resolve) => setTimeout(resolve, 600))
    log(`Opened ${value}`)
  }
</script>

{#snippet treeItems(nodes: TreeItemData[])}
  {#each nodes as item (item.value)}
    <TreeItem value={item.value}>
      <TreeItemLabel>
        {#snippet children(state)}
          {#if item.children}
            <TreeItemIndicator>
              <ChevronRightIcon aria-hidden="true" />
            </TreeItemIndicator>
          {/if}
          <span>{item.label}</span>
          {#if state.pending}
            <LoaderCircleIcon aria-hidden="true" />
          {/if}
        {/snippet}
      </TreeItemLabel>
      {#if item.children}
        <TreeGroup>
          {@render treeItems(item.children)}
        </TreeGroup>
      {/if}
    </TreeItem>
  {/each}
{/snippet}

<Tree
  aria-label="Project"
  {paths}
  defaultExpanded={["src"]}
  defaultValue="src/index.ts"
  activation="automatic"
  {onAction}
>
  {@render treeItems(items)}
</Tree>
```

用方向键下移到 package.json，然后按 Enter。打开期间它会显示加载指示器，随后控制台记录 Opened package.json。

## 选择
默认的 `mode="single"` 使用一个字符串值或 `null`。用 `"multiple"` 表示数组，或者当条目只应导航或执行动作时用 `"none"`。

单选模式下，`activation="automatic"` 会在方向键移动时选中。按压分支也会展开或折叠它；把 `expandOnPress` 设为 `false`，把展开交给指示器和方向键。

## 多选
`mode="multiple"` 让值变成数组。Cmd 点击或 Ctrl 点击切换一个条目，Shift 扩展范围，Cmd+A 或 Ctrl+A 选中可见的条目。这个示例把 `expandOnPress` 设为 `false`，所以点击 Inbox 或 Projects 会选中文件夹，而不折叠它。

```svelte title="multiple.svelte"
<script lang="ts">
  import { ChevronRightIcon } from "@lucide/svelte"
  import {
    Tree,
    TreeGroup,
    TreeItem,
    TreeItemIndicator,
    TreeItemLabel,
    type TreeItemData,
  } from "@ui-sdk/svelte/tree"
  import { useLog } from "./log"

  const items: TreeItemData[] = [
    {
      value: "inbox",
      label: "Inbox",
      children: [
        { value: "updates", label: "Updates" },
        { value: "forums", label: "Forums" },
        { value: "promotions", label: "Promotions" },
      ],
    },
    {
      value: "projects",
      label: "Projects",
      children: [
        { value: "website", label: "Website" },
        { value: "mobile", label: "Mobile app" },
      ],
    },
    { value: "archive", label: "Archive" },
    { value: "trash", label: "Trash" },
  ]

  const log = useLog()
</script>

{#snippet treeItems(nodes: TreeItemData[])}
  {#each nodes as item (item.value)}
    <TreeItem value={item.value}>
      <TreeItemLabel>
        {#if item.children}
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        {/if}
        {item.label}
      </TreeItemLabel>
      {#if item.children}
        <TreeGroup>
          {@render treeItems(item.children)}
        </TreeGroup>
      {/if}
    </TreeItem>
  {/each}
{/snippet}

<Tree
  aria-label="Folders"
  {items}
  mode="multiple"
  defaultValue={["updates", "website"]}
  onValueChange={(value) =>
    log(`${value.length} selected: ${value.join(", ")}`)}
  expandOnPress={false}
  defaultExpanded={["inbox", "projects"]}
>
  {@render treeItems(items)}
</Tree>
```

Cmd 点击或 Ctrl 点击 Archive，把它加入选择。Shift 点击或 Shift+方向键扩展范围，控制台会记录选中的内容。

## 复选框
添加 `checkable` 和 `TreeItemCheckbox`，得到一个独立于选择的勾选状态。Space 勾选获得焦点的条目。勾选分支会勾选它的后代，部分勾选的分支会报告混合状态。

`checkStrategy` 决定 `checked` 数组报告什么：

| 策略            | 报告的值                     |
| --------------- | ---------------------------- |
| `"leaf"`        | 已勾选的叶节点。这是默认值。 |
| `"trunk"`       | 最外层完全勾选的条目。       |
| `"branch"`      | 每个完全勾选的条目。         |
| `"independent"` | 每个条目各自独立，没有级联。 |

```svelte title="checkboxes.svelte"
<script lang="ts">
  import { ChevronRightIcon } from "@lucide/svelte"
  import {
    Tree,
    TreeGroup,
    TreeItem,
    TreeItemCheckbox,
    TreeItemIndicator,
    TreeItemLabel,
    type TreeItemData,
  } from "@ui-sdk/svelte/tree"
  import { useLog } from "./log"

  const items: TreeItemData[] = [
    {
      value: "frontend",
      label: "Frontend",
      children: [
        { value: "react", label: "React" },
        { value: "vue", label: "Vue" },
        { value: "svelte", label: "Svelte" },
      ],
    },
    {
      value: "backend",
      label: "Backend",
      children: [
        { value: "node", label: "Node" },
        {
          value: "databases",
          label: "Databases",
          children: [
            { value: "postgres", label: "Postgres" },
            { value: "sqlite", label: "SQLite" },
          ],
        },
      ],
    },
  ]

  const log = useLog()
</script>

{#snippet treeItems(nodes: TreeItemData[])}
  {#each nodes as item (item.value)}
    <TreeItem value={item.value}>
      <TreeItemLabel>
        {#if item.children}
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        {/if}
        <TreeItemCheckbox />
        {item.label}
      </TreeItemLabel>
      {#if item.children}
        <TreeGroup>
          {@render treeItems(item.children)}
        </TreeGroup>
      {/if}
    </TreeItem>
  {/each}
{/snippet}

<Tree
  aria-label="Stack"
  {items}
  checkable
  mode="none"
  checkStrategy="trunk"
  defaultChecked={["react", "postgres"]}
  onCheckedChange={(checked) =>
    log(`Checked ${checked.join(", ") || "nothing"}`)}
  defaultExpanded={["frontend", "backend", "databases"]}
>
  {@render treeItems(items)}
</Tree>
```

在 Vue 上按 Space，然后在 Frontend 上按。只有部分条目勾选时，Frontend 是混合状态，控制台会记录 trunk 策略的值。

## 链接
导航树设置 `mode="none"`，然后把标签渲染成链接。`current` 用 `aria-current="page"` 标识当前页，展开它的祖先，并给它初始的 Tab 停靠点。路由变化时更新它。

```svelte title="links.svelte"
<script lang="ts">
  import { ChevronRightIcon } from "@lucide/svelte"
  import {
    Tree,
    TreeGroup,
    TreeItem,
    TreeItemIndicator,
    TreeItemLabel,
    type TreeItemData,
  } from "@ui-sdk/svelte/tree"

  const pages: TreeItemData[] = [
    {
      value: "getting-started",
      label: "Getting started",
      children: [
        { value: "introduction", label: "Introduction", href: "#introduction" },
        { value: "installation", label: "Installation", href: "#installation" },
      ],
    },
    {
      value: "components",
      label: "Components",
      children: [
        { value: "accordion", label: "Accordion", href: "#accordion" },
        { value: "dialog", label: "Dialog", href: "#dialog" },
        { value: "tree", label: "Tree", href: "#tree" },
      ],
    },
    { value: "changelog", label: "Changelog", href: "#changelog" },
  ]

  const links = new Set(
    pages
      .flatMap((page) => [page, ...(page.children ?? [])])
      .filter((page) => page.href)
      .map((page) => page.value)
  )

  let current = $state("tree")
</script>

{#snippet treeItems(nodes: TreeItemData[])}
  {#each nodes as item (item.value)}
    {#snippet link({ props }: { props: Record<string, unknown> })}
      <a {...props} href={item.href}>{item.label}</a>
    {/snippet}
    <TreeItem value={item.value}>
      <TreeItemLabel render={item.href ? link : undefined}>
        {#if item.children}
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        {/if}
        {item.label}
      </TreeItemLabel>
      {#if item.children}
        <TreeGroup>
          {@render treeItems(item.children)}
        </TreeGroup>
      {/if}
    </TreeItem>
  {/each}
{/snippet}

<Tree
  aria-label="Docs"
  items={pages}
  mode="none"
  {current}
  onAction={(value, { event }) => {
    if (!links.has(value)) {
      return
    }
    event?.preventDefault()
    current = value
  }}
>
  {@render treeItems(pages)}
</Tree>
```

选择 Dialog。当前页标记会移到它上面，而你仍留在这个文档页。

## 禁用
禁用的条目无法被选中、勾选、展开或运行。它们仍然可以获得焦点，所以屏幕阅读器能找到它们。把 `focusableWhenDisabled` 设为 `false` 可以跳过它们，或者在根上设置 `disabled` 禁用整棵树。树外层禁用的 `<fieldset>` 也会禁用它。

```svelte title="disabled.svelte"
<script lang="ts">
  import { ChevronRightIcon } from "@lucide/svelte"
  import { Switch, SwitchThumb } from "@ui-sdk/svelte/switch"
  import {
    Tree,
    TreeGroup,
    TreeItem,
    TreeItemIndicator,
    TreeItemLabel,
    type TreeItemData,
  } from "@ui-sdk/svelte/tree"

  const items: TreeItemData[] = [
    {
      value: "plans",
      label: "Plans",
      children: [
        { value: "free", label: "Free" },
        { value: "pro", label: "Pro" },
        { value: "enterprise", label: "Enterprise", disabled: true },
      ],
    },
    {
      value: "legacy",
      label: "Legacy plans",
      disabled: true,
      children: [{ value: "starter", label: "Starter" }],
    },
    { value: "custom", label: "Custom" },
  ]

  let focusable = $state(true)
</script>

{#snippet treeItems(nodes: TreeItemData[])}
  {#each nodes as item (item.value)}
    <TreeItem value={item.value} disabled={item.disabled}>
      <TreeItemLabel>
        {#if item.children}
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        {/if}
        {item.label}
      </TreeItemLabel>
      {#if item.children}
        <TreeGroup>
          {@render treeItems(item.children)}
        </TreeGroup>
      {/if}
    </TreeItem>
  {/each}
{/snippet}

<div data-slot="stack">
  <div data-slot="controls">
    <label data-slot="label">
      <Switch bind:checked={focusable}>
        <SwitchThumb />
      </Switch>
      Focusable when disabled
    </label>
  </div>
  <Tree
    aria-label="Plans"
    {items}
    defaultExpanded={["plans"]}
    focusableWhenDisabled={focusable}
  >
    {@render treeItems(items)}
  </Tree>
</div>
```

在 Focusable when disabled 打开时用方向键经过 Enterprise。关掉它，同样的方向键会跳过禁用的条目。

## 加载子节点
在子节点存在之前，先把条目标记为 `branch`。`loadChildren` 在分支为空且第一次展开时运行。加载并渲染它的子节点，然后让 promise 兑现；子节点就绪后，树会展开这个分支。

用提供的 `signal` 取消请求。加载期间再次尝试展开分支会中止它。拒绝会设置 `data-failed`，下一次尝试会重试。`announcement` 让你自定义加载和失败的消息。

```svelte title="lazy.svelte"
<script lang="ts">
  import {
    ChevronRightIcon,
    LoaderCircleIcon,
    RotateCwIcon,
  } from "@lucide/svelte"
  import {
    Tree,
    TreeGroup,
    TreeItem,
    TreeItemIndicator,
    TreeItemLabel,
    type TreeAnnouncement,
  } from "@ui-sdk/svelte/tree"

  type Node = { value: string; label: string; branch?: boolean }

  const top: Node[] = [
    { value: "users", label: "users", branch: true },
    { value: "orders", label: "orders", branch: true },
    { value: "archive", label: "archive", branch: true },
  ]

  let archiveAsked = false
  async function fetchChildren(value: string, signal: AbortSignal) {
    await new Promise((resolve, reject) => {
      const timer = setTimeout(resolve, 800)
      signal.addEventListener(
        "abort",
        () => (clearTimeout(timer), reject(signal.reason))
      )
    })
    if (value === "archive" && !archiveAsked) {
      archiveAsked = true
      throw new Error("Network error")
    }
    return Array.from({ length: 3 }, (_, index) => ({
      value: `${value}/${index + 1}`,
      label: `${value.slice(0, -1)}_${index + 1}.json`,
    }))
  }

  let loaded: Record<string, Node[]> = $state({})

  async function loadChildren(
    value: string,
    { signal }: { signal: AbortSignal }
  ) {
    loaded[value] = await fetchChildren(value, signal)
  }

  const announcement = ({ type, label }: TreeAnnouncement) =>
    ({
      expanded: "Expanded",
      collapsed: "Collapsed",
      loading: `Loading ${label}`,
      "load-failed": `${label} didn't load. Try again.`,
    })[type]
</script>

{#snippet items(nodes: Node[])}
  {#each nodes as item (item.value)}
    <TreeItem value={item.value} branch={item.branch}>
      <TreeItemLabel>
        {#if item.branch}
          <TreeItemIndicator>
            {#snippet children(state)}
              {#if state.loading}
                <LoaderCircleIcon aria-hidden="true" />
              {:else if state.failed}
                <RotateCwIcon aria-hidden="true" />
              {:else}
                <ChevronRightIcon aria-hidden="true" />
              {/if}
            {/snippet}
          </TreeItemIndicator>
        {/if}
        {item.label}
      </TreeItemLabel>
      {#if loaded[item.value]}
        <TreeGroup>
          {@render items(loaded[item.value])}
        </TreeGroup>
      {/if}
    </TreeItem>
  {/each}
{/snippet}

<Tree aria-label="Database" {loadChildren} {announcement}>
  {@render items(top)}
</Tree>
```

展开 users 加载它的文件。Archive 第一次尝试会失败，并显示重试图标；再次展开它就能加载。

## 虚拟化
传入完整的 `items` 层级，用 `visibleTreeRows(items, expanded)` 把已展开的分支展平。按位置渲染附近的各行；即使 DOM 是扁平的，树仍提供正确的 ARIA 层级。

`onHighlight` 报告获得焦点的条目在可见行中的索引。在渲染范围之外的行挂载之前，用它来滚动。每个条目都会设置 `--tree-level`，所以样式表按层级缩进扁平的各行。

```svelte title="virtualized.svelte"
<script lang="ts">
  import { ChevronRightIcon } from "@lucide/svelte"
  import {
    Tree,
    TreeItem,
    TreeItemIndicator,
    TreeItemLabel,
    visibleTreeRows,
    type TreeItemData,
  } from "@ui-sdk/svelte/tree"

  const items: TreeItemData[] = Array.from({ length: 100 }, (_, folder) => ({
    value: `folder-${folder + 1}`,
    label: `Folder ${folder + 1}`,
    children: Array.from({ length: 100 }, (_, file) => ({
      value: `folder-${folder + 1}/file-${file + 1}`,
      label: `File ${file + 1}.txt`,
    })),
  }))

  const row = 32
  const height = 288

  let scroller: HTMLDivElement | undefined = $state()
  let scrollTop = $state(0)
  let expanded = $state(["folder-1"])
  const rows = $derived(visibleTreeRows(items, expanded))
  const start = $derived(Math.max(0, Math.floor(scrollTop / row) - 4))
  const end = $derived(
    Math.min(rows.length, Math.ceil((scrollTop + height) / row) + 4)
  )

  function onHighlight(_value: string, { index }: { index: number }) {
    const el = scroller
    if (!el) {
      return
    }
    const top = index * row
    if (top < el.scrollTop) {
      el.scrollTop = top
    } else if (top + row > el.scrollTop + el.clientHeight - 10) {
      el.scrollTop = top + row - el.clientHeight + 10
    }
    scrollTop = el.scrollTop
  }
</script>

<div
  data-slot="scroll"
  bind:this={scroller}
  onscroll={(event) => (scrollTop = event.currentTarget.scrollTop)}
>
  <Tree
    aria-label="Archive"
    {items}
    bind:expanded
    {onHighlight}
    style="height: {rows.length * row}px"
  >
    {#each rows.slice(start, end) as { item, index } (item.value)}
      <TreeItem value={item.value} style="top: {index * row}px">
        <TreeItemLabel>
          {#if item.children}
            <TreeItemIndicator>
              <ChevronRightIcon aria-hidden="true" />
            </TreeItemIndicator>
          {/if}
          {item.label}
        </TreeItemLabel>
      </TreeItem>
    {/each}
  </Tree>
</div>
```

展开文件夹，或按 End 聚焦 Folder 100。树有 10,100 个条目，但只渲染附近的行。

## 在页面中查找
`hiddenUntilFound` 用 `hidden="until-found"` 把折叠的分组留在 DOM 里。在支持它的浏览器里，在页面中查找能匹配隐藏的条目，并展开它的祖先。当你只需要折叠的内容保持挂载、不需要浏览器搜索时，使用 `keepMounted`。

```svelte title="find-in-page.svelte"
<script lang="ts">
  import { ChevronRightIcon } from "@lucide/svelte"
  import {
    Tree,
    TreeGroup,
    TreeItem,
    TreeItemIndicator,
    TreeItemLabel,
    type TreeItemData,
  } from "@ui-sdk/svelte/tree"

  const items: TreeItemData[] = [
    {
      value: "planets",
      label: "Planets",
      children: [
        { value: "mercury", label: "Mercury" },
        { value: "venus", label: "Venus" },
        {
          value: "earth",
          label: "Earth",
          children: [{ value: "moon", label: "The Moon" }],
        },
        {
          value: "mars",
          label: "Mars",
          children: [
            { value: "phobos", label: "Phobos" },
            { value: "deimos", label: "Deimos" },
          ],
        },
      ],
    },
    {
      value: "dwarf-planets",
      label: "Dwarf planets",
      children: [
        { value: "ceres", label: "Ceres" },
        {
          value: "pluto",
          label: "Pluto",
          children: [{ value: "charon", label: "Charon" }],
        },
      ],
    },
  ]
</script>

{#snippet treeItems(nodes: TreeItemData[])}
  {#each nodes as item (item.value)}
    <TreeItem value={item.value}>
      <TreeItemLabel>
        {#if item.children}
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        {/if}
        {item.label}
      </TreeItemLabel>
      {#if item.children}
        <TreeGroup>
          {@render treeItems(item.children)}
        </TreeGroup>
      {/if}
    </TreeItem>
  {/each}
{/snippet}

<Tree aria-label="Solar system" {items} hiddenUntilFound>
  {@render treeItems(items)}
</Tree>
```

用浏览器的查找命令查找 Phobos，火星的一颗卫星。匹配的分支会打开并显示它。

## 动画
分组把测量到的高度暴露为 `--tree-group-height`。在 `data-starting-style` 和 `data-ending-style` 之间，从这个高度过渡到零：

```css
[data-slot="tree-group"] {
  height: var(--tree-group-height);
  overflow: hidden;
  transition: height 150ms ease-out;

  &:is([data-starting-style], [data-ending-style]) {
    height: 0;
  }
}
```

分组会保持挂载，直到关闭动画结束。首次渲染就打开的分组，或由在页面中查找展开的分组，不会播放动画。

## 受控
选择、展开的分支和复选框互相独立：

| 值         | 形状                                | 变更通知           |
| ---------- | ----------------------------------- | ------------------ |
| `value`    | 一个字符串或 `null`；多选时是数组。 | `onValueChange`    |
| `expanded` | 一个分支值的数组。                  | `onExpandedChange` |
| `checked`  | 一个由勾选策略决定形状的数组。      | `onCheckedChange`  |

用 `bind:value`、`bind:expanded` 或 `bind:checked` 控制其中一个，或用 `defaultValue`、`defaultExpanded` 和 `defaultChecked` 设置起始状态。在变更回调里调用 `details.cancel()` 拒绝变更。[状态与事件](/docs/svelte/state-and-events)介绍了共享的绑定方式。

## 控制器
`createTreeController()` 实例可以展开或折叠分支、改变选择和复选框，或聚焦一个条目。`reveal(value)` 打开条目的祖先，把它滚动到视图中，并聚焦它。像这个示例一样通过 `items` 提供层级，或者让折叠的分组保持挂载，这样它们的后代仍然已知。设置和生命周期见[控制器](/docs/svelte/controllers)。

```svelte title="controller.svelte"
<script lang="ts">
  import { ChevronRightIcon } from "@lucide/svelte"
  import {
    createTreeController,
    Tree,
    TreeGroup,
    TreeItem,
    TreeItemIndicator,
    TreeItemLabel,
    type TreeItemData,
  } from "@ui-sdk/svelte/tree"

  const sections: TreeItemData[] = [
    {
      value: "account",
      label: "Account",
      children: [
        { value: "profile", label: "Profile" },
        {
          value: "security",
          label: "Security",
          children: [
            { value: "password", label: "Password" },
            { value: "two-factor", label: "Two-factor authentication" },
          ],
        },
      ],
    },
    {
      value: "workspace",
      label: "Workspace",
      children: [
        { value: "members", label: "Members" },
        { value: "billing", label: "Billing" },
      ],
    },
  ]

  const settings = createTreeController()
</script>

{#snippet items(nodes: TreeItemData[])}
  {#each nodes as item (item.value)}
    <TreeItem value={item.value}>
      <TreeItemLabel>
        {#if item.children}
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        {/if}
        {item.label}
      </TreeItemLabel>
      {#if item.children}
        <TreeGroup>
          {@render items(item.children)}
        </TreeGroup>
      {/if}
    </TreeItem>
  {/each}
{/snippet}

<div data-slot="stack">
  <div data-slot="controls">
    <button type="button" onclick={() => settings.expandAll()}
      >Expand All</button
    >
    <button type="button" onclick={() => settings.collapseAll()}
      >Collapse All</button
    >
    <button
      type="button"
      onclick={() => {
        settings.setValue("two-factor")
        settings.reveal("two-factor")
      }}
    >
      Find Two-Factor
    </button>
  </div>
  <Tree aria-label="Settings" items={sections} controller={settings}>
    {@render items(sections)}
  </Tree>
</div>
```

按 Find Two-Factor 打开 Account 和 Security，然后选中并聚焦 Two-factor authentication。Collapse All 会折叠每个分支。

## 自定义渲染
每个部件都接受一个 `render` snippet。链接示例把 `TreeItemLabel` 渲染成 `a`；标签里的链接把 Tab 顺序留给它的条目。`TreeItemLabel` 和 `TreeItemIndicator` 的 `children` snippet 也会收到条目的状态，文件路径和加载子节点示例用它来显示加载指示器。props 合并和基于状态的渲染见[部件与组合](/docs/svelte/parts-and-composition)。

## 样式
通过 `TreeItemLabel` 给每一行设置样式，它带有条目的 `data-selected`、`data-expanded`、`data-branch`、`data-current`、`data-disabled`、`data-loading`、`data-failed` 和 `data-pending`。条目自身的背景也会盖住它的子节点。焦点留在条目上，所以用 `:focus-visible` 给条目内获得焦点的行的标签设置样式。用指示器的 `data-expanded` 旋转它，并用 `--tree-level` 或每个分组的内边距缩进各行。

每个部件都有一个 `data-slot`，比如 `tree-label`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/svelte/components/tree#data-attributes)下。

### TreeItem
- `--tree-level`: The item's depth, 1 for a top-level item. Indent a flat tree with it.

### TreeGroup
- `--tree-group-height`: The group's content height in pixels while it animates, auto once expanded and 0px while collapsed.

## 数据属性
### TreeItem
`[data-slot="tree-item"]`

- `data-level` (`1`, `2`): The item's depth, from 1 at the top level. Also in the `--tree-level` variable.
- `data-branch`: Present on a branch: an item with children, or with `branch` set.
- `data-expanded`: Present while a branch is expanded.
- `data-indeterminate`: Present while only some of a branch is checked, with `checkable`.
- `data-selected`: Present while the item is selected.
- `data-current`: Present on the item for the current page, from `current`.
- `data-checked`: Present while the item's checkbox is checked, with `checkable`.
- `data-disabled`: Present when the item, or the whole tree, is disabled.
- `data-unchecked`: Present while the item's checkbox is unchecked, with `checkable`.
- `data-loading`: Present while `loadChildren` loads the branch's children.
- `data-failed`: Present after the branch's children failed to load, until it loads again.
- `data-pending`: Present while the item's `onAction` Promise hasn't settled.

### TreeItemLabel
`[data-slot="tree-label"]`

- `data-level` (`1`, `2`): The item's depth, from 1 at the top level. Also in the `--tree-level` variable.
- `data-branch`: Present on a branch: an item with children, or with `branch` set.
- `data-expanded`: Present while a branch is expanded.
- `data-selected`: Present while the item is selected.
- `data-current`: Present on the item for the current page, from `current`.
- `data-disabled`: Present when the item, or the whole tree, is disabled.
- `data-loading`: Present while `loadChildren` loads the branch's children.
- `data-failed`: Present after the branch's children failed to load, until it loads again.
- `data-pending`: Present while the item's `onAction` Promise hasn't settled.

### TreeItemIndicator
`[data-slot="tree-indicator"]`

- `data-level` (`1`): The item's depth, from 1 at the top level. Also in the `--tree-level` variable.
- `data-branch`: Present on a branch: an item with children, or with `branch` set.
- `data-expanded`: Present while a branch is expanded.
- `data-loading`: Present while `loadChildren` loads the branch's children.
- `data-failed`: Present after the branch's children failed to load, until it loads again.
- `data-pending`: Present while the item's `onAction` Promise hasn't settled.

### TreeItemCheckbox
`[data-slot="tree-checkbox"]`

- `data-indeterminate`: Present while only some of a branch is checked, with `checkable`.
- `data-checked`: Present while the item's checkbox is checked, with `checkable`.
- `data-unchecked`: Present while the item's checkbox is unchecked, with `checkable`.

### TreeGroup
`[data-slot="tree-group"]`

- `data-open`: Present while the group's branch is expanded.
- `data-closed`: Present while the group's branch is collapsed, including while it animates out.

## API 参考
### Tree
- `items?` (`TreeItemData[]`): The items as data: each a `value`, a `label` and, for a branch, `children`. Renders them for you, and gives the tree its whole shape even where rows aren't rendered.
- `paths?` (`readonly string[]`): Items from file paths, like `["src/index.ts", "README.md"]`: each folder becomes a branch, folders first. A path ending in `/` is an empty folder.
- `mode?` (`Mode`): How many items can be selected.
- `value?` (`TreeValue<Mode>`): The selected value. Pass it to control the selection. `null` selects nothing, and with `mode: "multiple"` it's a list.
- `defaultValue?` (`TreeValue<Mode>`): The value selected at first, when uncontrolled.
- `onValueChange?` (`((value: TreeValue<Mode>, details: ChangeDetails<TreeValueChangeReason>) => void)`): Runs when the selection wants to change. `details.reason` says why, and `details.cancel()` stops it.
- `activation?` (`"automatic" | "manual"`): Whether moving focus with the keyboard selects, with one item selectable: `"automatic"` selects the focused item, `"manual"` waits for Enter, Space or a press.
- `expanded?` (`string[]`): The expanded branches' values. Pass it to control which branches are open.
- `defaultExpanded?` (`string[]`): The branches expanded at first, when uncontrolled. The ancestors of `current` are added.
- `onExpandedChange?` (`((expanded: string[], details: ChangeDetails<TreeExpandedChangeReason>) => void)`): Runs when branches want to expand or collapse. `details.reason` says why, and `details.cancel()` stops it.
- `expandOnPress?` (`boolean`): Whether pressing a branch's row expands or collapses it. Its indicator always does.
- `checkable?` (`boolean`): Gives every item a tri-state checkbox, kept apart from the selection. Checking a branch checks everything in it, and a branch shows mixed while only some of it is checked. Space checks the focused item.
- `checked?` (`string[]`): The checked items' values, as `checkStrategy` reports them. Pass it to control the checkboxes.
- `defaultChecked?` (`string[]`): The items checked at first, when uncontrolled. A branch stands for everything in it.
- `onCheckedChange?` (`((checked: string[], details: ChangeDetails<TreeCheckedChangeReason>) => void)`): Runs when checkboxes want to change. `details.reason` says why, and `details.cancel()` stops it.
- `checkStrategy?` (`TreeCheckStrategy`): Which items the checked value lists: `"leaf"` the checked leaves, `"trunk"` the outermost fully checked items, `"branch"` every fully checked item, and `"independent"` each item on its own, with no cascading.
- `onAction?` (`((value: string, details: TreeActionDetails) => unknown)`): Runs when an item is pressed or Enter is pressed on it, apart from selecting it, like opening a file. Return a Promise to mark the item pending until it settles.
- `pendingAnnouncement?` (`string`): What screen readers hear once an item's action has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.
- `loadChildren?` (`((value: string, details: { signal: AbortSignal; }) => void | Promise<unknown>)`): Loads a branch's children the first time it expands while it has none. The branch shows `data-loading` and expands once the Promise resolves; a rejection marks it `data-failed` and the next expand tries again. Expanding it again while loading cancels through `signal`.
- `current?` (`string | null`): The value of the item for the current page. It gets `aria-current="page"`, takes the tab stop first, and its ancestors expand, at first and whenever it changes.
- `onHighlight?` (`((value: string, details: ListHighlightDetails) => void)`): Runs when the keyboard moves focus to an item, with its row among the items that show, from 0. A virtualized list scrolls that row into view here, so an item it hasn't rendered can take focus once it does.
- `disabled?` (`boolean`): Disables every item. Items stay focusable unless `focusableWhenDisabled` is false.
- `focusableWhenDisabled?` (`boolean`): Whether disabled items take focus, so a screen reader still finds them.
- `keepMounted?` (`boolean`): Whether collapsed branches keep their groups in the page, hidden.
- `hiddenUntilFound?` (`boolean`): Keeps collapsed groups in the page as `hidden="until-found"`, so the browser's find in page can match their text and expand them.
- `announcement?` (`((change: TreeAnnouncement) => string | null | undefined)`): What screen readers hear when a branch expands, collapses, starts loading or fails to load. Return null for nothing. Expanding and collapsing are announced on Apple platforms only, where VoiceOver doesn't read the change.
- `controller?` (`object`): Drives the tree from anywhere. Create one with `createTreeController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### TreeItem
- `value` (`string`): Identifies the item, unique in the tree. Passed to `onAction`, and listed by the value, `expanded` and `checked`.
- `branch?` (`boolean`): Whether it's a branch. Adapters set it when it has a group; set it yourself for a branch whose children load later.
- `disabled?` (`boolean`): Stops it from being selected, checked, expanded or run. It stays focusable unless `focusableWhenDisabled` is false.
- `label?` (`string`): The text typeahead matches, when its label isn't plain text.

### TreeGroup
- `keepMounted?` (`boolean`): Whether the group stays in the page, hidden, while collapsed. Overrides the tree's.
- `hiddenUntilFound?` (`boolean`): Whether the group stays findable with `hidden="until-found"` while collapsed. Overrides the tree's.

### 以数据形式提供的条目
`items` 里的每个条目：

- `value` (`string`): Identifies the item. Unique in the tree.
- `label` (`string`): What it shows, and what typeahead matches.
- `children?` (`TreeItemData[]`): Its children. Leave it out for a leaf. An empty array is a branch with no children, or one whose children load when it opens.
- `disabled?` (`boolean`): Whether it can't be selected, checked or activated. It can still take focus.
- `href?` (`string`): Makes the item a link to this address.

`visibleTreeRows(items, expanded)` 为扁平列表返回的每一行：

- `item` (`TreeItemData`): The object from your data this row shows, the same one you passed in, children included.
- `parent` (`string | null`): The value of the item it's nested in, or `null` at the top level.
- `level` (`number`): Its depth, 1 at the top level.
- `index` (`number`): Its place among the rows that show, from 0, for a virtualized list.

### 状态
每个部件的 `render` 和 `children` snippet 会收到什么。

`Tree`:

- `mode` (`TreeMode`): How many items can be selected.
- `checkable` (`boolean`): Whether items have checkboxes.
- `disabled` (`boolean`): Whether the whole tree is disabled, by its `disabled` option or a disabled fieldset around it.

`TreeItem`，以及它的 `TreeItemLabel`、`TreeItemIndicator` 和 `TreeItemCheckbox`：

- `expanded` (`boolean`): Whether it's a branch that's expanded.
- `selected` (`boolean`): Whether its value is in the tree's value. Separate from `checked`, which its checkbox sets.
- `checked` (`TreeCheckedState`): Its checkbox: checked, unchecked or `"indeterminate"`. False without `checkable`.
- `disabled` (`boolean`): Whether it can't be selected, checked, expanded or run.
- `branch` (`boolean`): Whether it has children, or can load them.
- `level` (`number`): Its depth, 1 at the top level.
- `current` (`boolean`): Whether it's the current page's item.
- `loading` (`boolean`): Whether its children are loading.
- `failed` (`boolean`): Whether loading its children failed.
- `pending` (`boolean`): Whether its `onAction` is still running.

`TreeGroup`:

- `expanded` (`boolean`): Whether its branch is expanded.
- `level` (`number`): The depth of the items in it.

### 原因
分支为什么展开或折叠：

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `trigger-press` (`MouseEvent | KeyboardEvent | TouchEvent`): Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its `touchend`.
- `list-navigation` (`KeyboardEvent`): Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
- `find-in-page` (`Event`): The browser's find in page matched hidden content.
- `imperative` (`none`): A controller or `api` call.

选择为什么变化：

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `list-navigation` (`KeyboardEvent`): Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
- `imperative` (`none`): A controller or `api` call.

以及复选框为什么变化：

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `imperative` (`none`): A controller or `api` call.

### 控制器
用 `createTreeController()` 创建一个，并作为 `controller` 传入。

- `getExpanded()` (`() => string[]`): The values of the expanded branches.
- `setExpanded(expanded, options?)` (`(expanded: string[], options?: TreeChangeOptions<TreeExpandedChangeReason> | undefined) => boolean`): Expands exactly these branches. Returns false when canceled.
- `isExpanded(value)` (`(value: string) => boolean`): Whether a branch is expanded.
- `expand(value, options?)` (`(value: string, options?: TreeChangeOptions<TreeExpandedChangeReason> | undefined) => boolean`): Expands a branch, loading its children first with `loadChildren` when it has none.
- `collapse(value, options?)` (`(value: string, options?: TreeChangeOptions<TreeExpandedChangeReason> | undefined) => boolean`): Collapses a branch. Focus inside it moves to the branch.
- `toggle(value, options?)` (`(value: string, options?: TreeChangeOptions<TreeExpandedChangeReason> | undefined) => boolean`): Expands a collapsed branch, or collapses an expanded one.
- `expandAll(options?)` (`(options?: TreeChangeOptions<TreeExpandedChangeReason> | undefined) => boolean`): Expands every branch, and every branch that renders inside one later.
- `collapseAll(options?)` (`(options?: TreeChangeOptions<TreeExpandedChangeReason> | undefined) => boolean`): Collapses every branch.
- `getValue()` (`() => string | string[] | null`): The selected value: a value or `null`, or a list with `mode: "multiple"`.
- `setValue(value, options?)` (`(value: string | string[] | null, options?: TreeChangeOptions<TreeValueChangeReason> | undefined) => boolean`): Selects these items.
- `getChecked()` (`() => string[]`): The checked value, as `checkStrategy` reports it.
- `setChecked(checked, options?)` (`(checked: string[], options?: TreeChangeOptions<TreeCheckedChangeReason> | undefined) => boolean`): Sets the checked value.
- `checkedState(value)` (`(value: string) => TreeCheckedState`): Whether an item's checkbox is checked, unchecked or `"indeterminate"`.
- `reveal(value)` (`(value: string) => void`): Expands an item's ancestors, scrolls it into view and focuses it.
- `focus(value?)` (`(value?: string | undefined) => void`): Focuses an item, or the item with the tab stop.

## 无障碍
树遵循 [WAI-ARIA 树视图模式](https://www.w3.org/WAI/ARIA/apg/patterns/treeview/)。条目的角色是 `treeitem`，带有 `aria-level`，分支上带有 `aria-expanded`，树可勾选时带有 `aria-checked`。

### 键盘
树只有一个 Tab 停靠点。Tab 从当前页、选中的条目或第一个条目进入，之后回到最后聚焦的条目。

| 按键                        | 作用                                   |
| --------------------------- | -------------------------------------- |
| Down / Up Arrow             | 聚焦下一个或上一个可见条目。           |
| Right Arrow                 | 展开分支，或进入它的第一个子节点。     |
| Left Arrow                  | 折叠分支，或聚焦它的父节点。           |
| Home / End                  | 聚焦第一个或最后一个可见条目。         |
| Alt+Right / Alt+Left Arrow  | 展开或折叠分支及其后代。               |
| `*`                         | 展开同级分支。                         |
| Enter                       | 选中并运行条目的动作，或跟随它的链接。 |
| Space                       | 树可勾选时勾选条目，否则选中它。       |
| Shift+Down / Shift+Up Arrow | 扩展多选。                             |
| Cmd+A / Ctrl+A              | 在多选模式下选中可见条目。             |
| Typing                      | 聚焦下一个标签以该文本开头的条目。     |

Option 在 Mac 上是 Alt。在从右到左的文本中，Left 和 Right 互换。

### 经过测试的行为
下面每一行都是一个自动化测试。

**Expanding and collapsing**

- Branches start collapsed, and only top-level items show.
- Clicking a branch expands it and shows its children.
- Clicking the indicator expands without selecting.
- A change can be canceled.
- A default can expand nested branches.
- A controller expands and collapses everything.
- Reveal expands an item's ancestors and focuses it.

**Keyboard**

- Tab reaches the tree once, on the first item.
- Down and Up move between the items that show.
- Right expands a branch, then moves to its first child.
- Right on a leaf does nothing.
- Left collapses a branch, then moves to its parent.
- Home and End move to the first and last items that show.
- * expands every branch beside the focused item.
- Alt+Right expands a branch and everything in it.
- Typing moves to the next item that starts with the text.
- Enter selects the item and runs its action.
- A key on a nested item acts on that item only.

**Selection**

- Clicking an item selects it alone.
- The selected item takes the tab stop.
- Disabled items take focus but can't be selected.
- With multiple selection, Shift+Down extends and Ctrl+A selects everything.
- With automatic activation, moving focus selects.
- Without selection, items have no aria-selected.

**Checkboxes**

- Checking a branch checks everything in it.
- Space checks the focused item, and a disabled item keeps its check.
- Checking a leaf leaves the selection and the branch alone.

**Positions**

- Every item says its level and place among its siblings.
- The current page's item is marked.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器记录：

- Announcements while using the tree with a keyboard.
- Expanding the focused item is announced on Apple platforms.
- Nothing is announced elsewhere, where screen readers read the change.

Runs in React、Vue 和 web components.
