# Tree

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

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

```ts title="demo.ts"
import "@ui-sdk/web/tree"
import {
  ChevronRight,
  createElement,
  File,
  Folder,
  FolderOpen,
  type IconNode,
} from "lucide"

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" },
]

const icon = (node: IconNode) =>
  createElement(node, { "aria-hidden": "true" }).outerHTML

function markup(items: Node[]) {
  let html = ""
  for (const item of items) {
    html += `
      <ui-tree-item value="${item.value}">
        <ui-tree-item-label>
          ${
            item.children
              ? `<ui-tree-item-indicator>${icon(ChevronRight)}</ui-tree-item-indicator>
                ${icon(Folder)}
                ${icon(FolderOpen)}`
              : icon(File)
          }
          <span>${item.label}</span>
        </ui-tree-item-label>
        ${item.children ? `<ui-tree-group>${markup(item.children)}</ui-tree-group>` : ""}
      </ui-tree-item>`
  }
  return html
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-tree aria-label="Files" default-expanded="app" default-value="app/page.tsx">
      ${markup(files)}
    </ui-tree>
  `
}

export { mount }
```

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

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

导入组件会定义它的元素。在服务器上，导入什么也不做。

```ts
import "@ui-sdk/web/tree"
```

## 组合
用下面的组合构建 `ui-tree`：

```text
ui-tree
├── ui-tree-item
│   ├── ui-tree-item-label
│   │   └── ui-tree-item-indicator
│   └── ui-tree-group
│       └── ui-tree-item
│           └── ui-tree-item-label
└── ui-tree-item
    └── ui-tree-item-label
```

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

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

```html
<script type="module">
  import "@ui-sdk/web/tree"
</script>

<ui-tree aria-label="Project files">
  <ui-tree-item value="src">
    <ui-tree-item-label>
      <ui-tree-item-indicator>›</ui-tree-item-indicator>
      src
    </ui-tree-item-label>
    <ui-tree-group>
      <ui-tree-item value="src/index.ts">
        <ui-tree-item-label>index.ts</ui-tree-item-label>
      </ui-tree-item>
    </ui-tree-group>
  </ui-tree-item>
  <ui-tree-item value="package.json">
    <ui-tree-item-label>package.json</ui-tree-item-label>
  </ui-tree-item>
</ui-tree>
```

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

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

const tree = document.querySelector('ui-tree[aria-label="Groceries"]')!
tree.items = items
```

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

```ts
function markup(items: TreeItemData[]) {
  let html = ""
  for (const item of items)
    html += `
      <ui-tree-item value="${item.value}">
        <ui-tree-item-label>${item.label}</ui-tree-item-label>
        ${item.children ? `<ui-tree-group>${markup(item.children)}</ui-tree-group>` : ""}
      </ui-tree-item>`
  return html
}

const tree = document.querySelector('ui-tree[aria-label="Groceries"]')!
tree.innerHTML = markup(items)
tree.items = items
```

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

选择和激活是分开的。这个示例设置 `activation="automatic"`，方向键会选中文件，然后由 `action` 事件打开它。把 promise 传给事件的 `detail.waitUntil()`，打开期间就会显示待处理状态。

```ts title="paths.ts"
import { treeFromPaths, type TreeItemData } from "@ui-sdk/core/tree"
import "@ui-sdk/web/tree"
import { ChevronRight, createElement, LoaderCircle } from "lucide"
import { log } 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("/")))

function markup(items: TreeItemData[]) {
  let html = ""
  for (const item of items) {
    html += `
      <ui-tree-item value="${item.value}">
        <ui-tree-item-label>
          ${
            item.children
              ? `<ui-tree-item-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-tree-item-indicator>`
              : ""
          }
          <span>${item.label}</span>
          ${createElement(LoaderCircle, { "aria-hidden": "true", "data-show": "pending" }).outerHTML}
        </ui-tree-item-label>
        ${item.children ? `<ui-tree-group>${markup(item.children)}</ui-tree-group>` : ""}
      </ui-tree-item>`
  }
  return html
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-tree aria-label="Project" default-expanded="src" default-value="src/index.ts" activation="automatic">
      ${markup(items)}
    </ui-tree>
  `
  const tree = root.querySelector("ui-tree")!
  tree.paths = paths
  tree.addEventListener("action", (event) => {
    const { value, waitUntil } = event.detail
    if (!files.has(value)) {
      return
    }
    waitUntil(
      new Promise((resolve) => setTimeout(resolve, 600)).then(() =>
        log(root, `Opened ${value}`)
      )
    )
  })
}

export { mount }
```

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

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

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

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

```ts title="multiple.ts"
import type { TreeItemData } from "@ui-sdk/core/tree"
import "@ui-sdk/web/tree"
import { ChevronRight, createElement } from "lucide"
import { log } 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" },
]

function markup(items: TreeItemData[]) {
  let html = ""
  for (const item of items) {
    html += `
      <ui-tree-item value="${item.value}">
        <ui-tree-item-label>
          ${
            item.children
              ? `<ui-tree-item-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-tree-item-indicator>`
              : ""
          }
          ${item.label}
        </ui-tree-item-label>
        ${item.children ? `<ui-tree-group>${markup(item.children)}</ui-tree-group>` : ""}
      </ui-tree-item>`
  }
  return html
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-tree aria-label="Folders" mode="multiple" default-value="updates,website" expand-on-press="false" default-expanded="inbox,projects">
      ${markup(items)}
    </ui-tree>
  `
  const tree = root.querySelector("ui-tree")!
  tree.items = items
  tree.addEventListener("valuechange", (event) => {
    const value = event.detail.value as string[]
    log(root, `${value.length} selected: ${value.join(", ")}`)
  })
}

export { mount }
```

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

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

`check-strategy` 决定 `checked` 数组报告什么：

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

```ts title="checkboxes.ts"
import type { TreeItemData } from "@ui-sdk/core/tree"
import "@ui-sdk/web/tree"
import { ChevronRight, createElement } from "lucide"
import { log } 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" },
        ],
      },
    ],
  },
]

function markup(items: TreeItemData[]) {
  let html = ""
  for (const item of items) {
    html += `
      <ui-tree-item value="${item.value}">
        <ui-tree-item-label>
          ${
            item.children
              ? `<ui-tree-item-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-tree-item-indicator>`
              : ""
          }
          <ui-tree-item-checkbox></ui-tree-item-checkbox>
          ${item.label}
        </ui-tree-item-label>
        ${item.children ? `<ui-tree-group>${markup(item.children)}</ui-tree-group>` : ""}
      </ui-tree-item>`
  }
  return html
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-tree aria-label="Stack" checkable mode="none" check-strategy="trunk" default-checked="react,postgres" default-expanded="frontend,backend,databases">
      ${markup(items)}
    </ui-tree>
  `
  const tree = root.querySelector("ui-tree")!
  tree.items = items
  tree.addEventListener("checkedchange", (event) => {
    log(root, `Checked ${event.detail.value.join(", ") || "nothing"}`)
  })
}

export { mount }
```

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

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

```ts title="links.ts"
import type { TreeItemData } from "@ui-sdk/core/tree"
import "@ui-sdk/web/tree"
import { ChevronRight, createElement } from "lucide"

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)
)

function markup(items: TreeItemData[]) {
  let html = ""
  for (const item of items) {
    const content = `
      ${
        item.children
          ? `<ui-tree-item-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-tree-item-indicator>`
          : ""
      }
      ${item.label}`
    html += `
      <ui-tree-item value="${item.value}">
        ${
          item.href
            ? `<ui-tree-item-label as-child><a href="${item.href}">${content}</a></ui-tree-item-label>`
            : `<ui-tree-item-label>${content}</ui-tree-item-label>`
        }
        ${item.children ? `<ui-tree-group>${markup(item.children)}</ui-tree-group>` : ""}
      </ui-tree-item>`
  }
  return html
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-tree aria-label="Docs" mode="none" current="tree">
      ${markup(pages)}
    </ui-tree>
  `
  const tree = root.querySelector("ui-tree")!
  tree.items = pages
  tree.addEventListener("action", (event) => {
    const { value, event: trigger } = event.detail
    if (!links.has(value)) {
      return
    }
    trigger?.preventDefault()
    tree.setAttribute("current", value)
  })
}

export { mount }
```

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

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

```ts title="disabled.ts"
import type { TreeItemData } from "@ui-sdk/core/tree"
import "@ui-sdk/web/switch"
import "@ui-sdk/web/tree"
import { ChevronRight, createElement } from "lucide"

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" },
]

function markup(items: TreeItemData[]) {
  let html = ""
  for (const item of items) {
    html += `
      <ui-tree-item value="${item.value}"${item.disabled ? " disabled" : ""}>
        <ui-tree-item-label>
          ${
            item.children
              ? `<ui-tree-item-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-tree-item-indicator>`
              : ""
          }
          ${item.label}
        </ui-tree-item-label>
        ${item.children ? `<ui-tree-group>${markup(item.children)}</ui-tree-group>` : ""}
      </ui-tree-item>`
  }
  return html
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <ui-switch default-checked>
            <ui-switch-thumb></ui-switch-thumb>
          </ui-switch>
          Focusable when disabled
        </label>
      </div>
      <ui-tree aria-label="Plans" default-expanded="plans">
        ${markup(items)}
      </ui-tree>
    </div>
  `
  const tree = root.querySelector("ui-tree")!
  tree.items = items
  root
    .querySelector("ui-switch")!
    .addEventListener("checkedchange", (event) => {
      tree.setAttribute("focusable-when-disabled", String(event.detail.value))
    })
}

export { mount }
```

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

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

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

```ts title="lazy.ts"
import "@ui-sdk/web/tree"
import {
  ChevronRight,
  createElement,
  LoaderCircle,
  RotateCw,
  type IconNode,
} from "lucide"

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`,
  }))
}

const icon = (node: IconNode, show: string) =>
  createElement(node, { "aria-hidden": "true", "data-show": show }).outerHTML

const markup = (items: Node[]) =>
  items
    .map(
      (item) => `
        <ui-tree-item value="${item.value}"${item.branch ? " branch" : ""}>
          <ui-tree-item-label>
            ${
              item.branch
                ? `<ui-tree-item-indicator>
                    ${icon(LoaderCircle, "loading")}
                    ${icon(RotateCw, "failed")}
                    ${icon(ChevronRight, "idle")}
                  </ui-tree-item-indicator>`
                : ""
            }
            ${item.label}
          </ui-tree-item-label>
        </ui-tree-item>`
    )
    .join("")

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-tree aria-label="Database">
      ${markup(top)}
    </ui-tree>
  `
  const tree = root.querySelector("ui-tree")!
  tree.loadChildren = async (value, { signal }) => {
    const children = await fetchChildren(value, signal)
    tree
      .querySelector(`ui-tree-item[value="${value}"]`)!
      .insertAdjacentHTML(
        "beforeend",
        `<ui-tree-group>${markup(children)}</ui-tree-group>`
      )
  }
  tree.announcement = ({ type, label }) =>
    ({
      expanded: "Expanded",
      collapsed: "Collapsed",
      loading: `Loading ${label}`,
      "load-failed": `${label} didn't load. Try again.`,
    })[type]
}

export { mount }
```

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

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

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

```ts title="virtualized.ts"
import { visibleTreeRows, type TreeItemData } from "@ui-sdk/core/tree"
import "@ui-sdk/web/tree"
import { ChevronRight, createElement } from "lucide"

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

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="scroll">
      <ui-tree aria-label="Archive" default-expanded="folder-1"></ui-tree>
    </div>
  `
  const scroller = root.querySelector("div")!
  const tree = root.querySelector("ui-tree")!

  let rows = visibleTreeRows(items, ["folder-1"])

  const rendered = new Map<string, HTMLElement>()
  const render = () => {
    tree.style.height = `${rows.length * row}px`
    const start = Math.max(0, Math.floor(scroller.scrollTop / row) - 4)
    const end = Math.min(
      rows.length,
      Math.ceil((scroller.scrollTop + height) / row) + 4
    )
    const visible = new Map(
      rows.slice(start, end).map((entry) => [entry.item.value, entry])
    )
    for (const [value, el] of rendered) {
      if (visible.has(value)) {
        continue
      }
      el.remove()
      rendered.delete(value)
    }
    for (const [value, { item, index }] of visible) {
      let el = rendered.get(value)
      if (!el) {
        tree.insertAdjacentHTML(
          "beforeend",
          `<ui-tree-item value="${item.value}">
            <ui-tree-item-label>
              ${
                item.children
                  ? `<ui-tree-item-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-tree-item-indicator>`
                  : ""
              }
              ${item.label}
            </ui-tree-item-label>
          </ui-tree-item>`
        )
        el = tree.lastElementChild as HTMLElement
        rendered.set(value, el)
      }
      el.style.top = `${index * row}px`
    }
  }
  render()
  tree.items = items
  scroller.addEventListener("scroll", render)
  tree.addEventListener("expandedchange", (event) => {
    rows = visibleTreeRows(items, event.detail.value)
    render()
  })
  tree.addEventListener("highlight", (event) => {
    const { index } = event.detail
    const top = index * row
    if (top < scroller.scrollTop) {
      scroller.scrollTop = top
    } else if (top + row > scroller.scrollTop + scroller.clientHeight - 10) {
      scroller.scrollTop = top + row - scroller.clientHeight + 10
    }
    render()
  })
}

export { mount }
```

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

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

```ts title="find-in-page.ts"
import type { TreeItemData } from "@ui-sdk/core/tree"
import "@ui-sdk/web/tree"
import { ChevronRight, createElement } from "lucide"

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" }],
      },
    ],
  },
]

function markup(items: TreeItemData[]) {
  let html = ""
  for (const item of items) {
    html += `
      <ui-tree-item value="${item.value}">
        <ui-tree-item-label>
          ${
            item.children
              ? `<ui-tree-item-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-tree-item-indicator>`
              : ""
          }
          ${item.label}
        </ui-tree-item-label>
        ${item.children ? `<ui-tree-group>${markup(item.children)}</ui-tree-group>` : ""}
      </ui-tree-item>`
  }
  return html
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-tree aria-label="Solar system" hidden-until-found>
      ${markup(items)}
    </ui-tree>
  `
  root.querySelector("ui-tree")!.items = items
}

export { mount }
```

用浏览器的查找命令查找 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`；多选时是数组。 | `valuechange`    |
| `expanded` | 一个分支值的数组。                  | `expandedchange` |
| `checked`  | 一个由勾选策略决定形状的数组。      | `checkedchange`  |

在元素上读取或设置这些 property，并监听它们的变更事件，或用 `default-value`、`default-expanded` 和 `default-checked` 设置起始状态。在变更事件里调用 `event.preventDefault()` 拒绝变更。[状态与事件](/docs/web-components/state-and-events)介绍了共享的绑定方式。

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

```ts title="controller.ts"
import type { TreeItemData } from "@ui-sdk/core/tree"
import "@ui-sdk/web/tree"
import { ChevronRight, createElement } from "lucide"

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" },
    ],
  },
]

function markup(items: TreeItemData[]) {
  let html = ""
  for (const item of items) {
    html += `
      <ui-tree-item value="${item.value}">
        <ui-tree-item-label>
          ${
            item.children
              ? `<ui-tree-item-indicator>${createElement(ChevronRight, { "aria-hidden": "true" }).outerHTML}</ui-tree-item-indicator>`
              : ""
          }
          ${item.label}
        </ui-tree-item-label>
        ${item.children ? `<ui-tree-group>${markup(item.children)}</ui-tree-group>` : ""}
      </ui-tree-item>`
  }
  return html
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button">Expand All</button>
        <button type="button">Collapse All</button>
        <button type="button">Find Two-Factor</button>
      </div>
      <ui-tree aria-label="Settings">
        ${markup(sections)}
      </ui-tree>
    </div>
  `
  const tree = root.querySelector("ui-tree")!
  const [expand, collapse, find] = root.querySelectorAll("button")
  tree.items = sections
  expand.addEventListener("click", () => tree.api.expandAll())
  collapse.addEventListener("click", () => tree.api.collapseAll())
  find.addEventListener("click", () => {
    tree.api.setValue("two-factor")
    tree.api.reveal("two-factor")
  })
}

export { mount }
```

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

## 自定义渲染
元素没有 render 函数。链接示例用 `as-child` 把 `ui-tree-item-label` 绑定到 `a`；标签里的链接把 Tab 顺序留给它的条目。把任何东西放进部件，并通过部件的数据属性显示它，就像文件路径和加载子节点示例用 `data-pending` 和 `data-loading` 显示加载指示器那样。绑定你自己的元素见[部件与组合](/docs/web-components/parts-and-composition)。

## 样式
通过 `ui-tree-item-label` 给每一行设置样式，它带有条目的 `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/web-components/components/tree#data-attributes)下。

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

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

## 数据属性
### `<ui-tree-item>`
`[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.

### `<ui-tree-item-label>`
`[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.

### `<ui-tree-item-indicator>`
`[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.

### `<ui-tree-item-checkbox>`
`[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`.

### `<ui-tree-group>`
`[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 参考
props 是 kebab 写法的属性，比如 `mode` 和 `default-expanded`。列表，比如 `expanded`，是用逗号分隔的值。`items`、`paths`、`loadChildren`、`announcement` 和 `controller` 是 property。回调是 `<ui-tree>` 上的 DOM 事件，不冒泡，新状态在 `event.detail.value` 里，`reason` 和 `event` 在它旁边。

### 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.
- `valuechange event`: 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.
- `expandedchange event`: 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.
- `checkedchange event`: 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.
- `action event`: 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.
- `highlight event`: 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 `action`, 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.

### 状态
同样的状态会作为数据属性显示在每个元素上。

`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.

### 控制器
元素的 `api` property 有同样的方法。

- `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.
