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

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

"use client"

import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
} from "@ui-sdk/react/tree"
import {
  ChevronRightIcon,
  FileIcon,
  FolderIcon,
  FolderOpenIcon,
} from "lucide-react"

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

function Items({ items }: { items: Node[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value}>
      <TreeItemLabel>
        {item.children ? (
          <>
            <TreeItemIndicator>
              <ChevronRightIcon aria-hidden="true" />
            </TreeItemIndicator>
            <FolderIcon aria-hidden="true" />
            <FolderOpenIcon aria-hidden="true" />
          </>
        ) : (
          <FileIcon aria-hidden="true" />
        )}
        <span>{item.label}</span>
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

function Example() {
  return (
    <Tree
      aria-label="Files"
      defaultExpanded={["app"]}
      defaultValue="app/page.tsx"
    >
      <Items items={files} />
    </Tree>
  )
}

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

安装

npm install @ui-sdk/react @ui-sdk/core

组合

用下面的组合构建 Tree:

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

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

用法

导入部件并把它们组合起来:

import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
} from "@ui-sdk/react/tree"

function Example() {
  return (
    <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>
  )
}

export { Example }

以数据形式提供的条目

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

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

function Example() {
  return <Tree aria-label="Groceries" items={items} />
}

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

function Items({ items }: { items: TreeItemData[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value}>
      <TreeItemLabel>{item.label}</TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

function Example() {
  return (
    <Tree aria-label="Groceries" items={items}>
      <Items items={items} />
    </Tree>
  )
}

文件路径

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

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

控制台
"use client"

import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
  treeFromPaths,
  type TreeItemData,
} from "@ui-sdk/react/tree"
import { ChevronRightIcon, LoaderCircleIcon } from "lucide-react"
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("/")))

function Items({ items }: { items: TreeItemData[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value}>
      <TreeItemLabel>
        {(state) => (
          <>
            {item.children && (
              <TreeItemIndicator>
                <ChevronRightIcon aria-hidden="true" />
              </TreeItemIndicator>
            )}
            <span>{item.label}</span>
            {state.pending && <LoaderCircleIcon aria-hidden="true" />}
          </>
        )}
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

function Example() {
  const log = useLog()
  return (
    <Tree
      aria-label="Project"
      paths={paths}
      defaultExpanded={["src"]}
      defaultValue="src/index.ts"
      activation="automatic"
      onAction={async (value) => {
        if (!files.has(value)) {
          return
        }
        await new Promise((resolve) => setTimeout(resolve, 600))
        log(`Opened ${value}`)
      }}
    >
      <Items items={items} />
    </Tree>
  )
}

export { Example }
用方向键下移到 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 会选中文件夹,而不折叠它。

控制台
"use client"

import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
  type TreeItemData,
} from "@ui-sdk/react/tree"
import { ChevronRightIcon } from "lucide-react"
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" },
]

function Items({ items }: { items: TreeItemData[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value}>
      <TreeItemLabel>
        {item.children && (
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        )}
        {item.label}
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

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

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

复选框

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

checkStrategy 决定 checked 数组报告什么:

策略报告的值
"leaf"已勾选的叶节点。这是默认值。
"trunk"最外层完全勾选的条目。
"branch"每个完全勾选的条目。
"independent"每个条目各自独立,没有级联。
控制台
"use client"

import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemCheckbox,
  TreeItemIndicator,
  TreeItemLabel,
  type TreeItemData,
} from "@ui-sdk/react/tree"
import { ChevronRightIcon } from "lucide-react"
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" },
        ],
      },
    ],
  },
]

function Items({ items }: { items: TreeItemData[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value}>
      <TreeItemLabel>
        {item.children && (
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        )}
        <TreeItemCheckbox />
        {item.label}
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

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

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

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

"use client"

import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
  type TreeItemData,
} from "@ui-sdk/react/tree"
import { ChevronRightIcon } from "lucide-react"
import * as React from "react"

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 Items({ items }: { items: TreeItemData[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value}>
      <TreeItemLabel render={item.href ? <a href={item.href} /> : undefined}>
        {item.children && (
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        )}
        {item.label}
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

function Example() {
  const [current, setCurrent] = React.useState("tree")
  return (
    <Tree
      aria-label="Docs"
      items={pages}
      mode="none"
      current={current}
      onAction={(value, { event }) => {
        if (!links.has(value)) {
          return
        }
        event?.preventDefault()
        setCurrent(value)
      }}
    >
      <Items items={pages} />
    </Tree>
  )
}

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

禁用

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

"use client"

import { Switch, SwitchThumb } from "@ui-sdk/react/switch"
import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
  type TreeItemData,
} from "@ui-sdk/react/tree"
import { ChevronRightIcon } from "lucide-react"
import * as React from "react"

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 Items({ items }: { items: TreeItemData[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value} disabled={item.disabled}>
      <TreeItemLabel>
        {item.children && (
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        )}
        {item.label}
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

function Example() {
  const [focusable, setFocusable] = React.useState(true)
  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <Switch checked={focusable} onCheckedChange={setFocusable}>
            <SwitchThumb />
          </Switch>
          Focusable when disabled
        </label>
      </div>
      <Tree
        aria-label="Plans"
        items={items}
        defaultExpanded={["plans"]}
        focusableWhenDisabled={focusable}
      >
        <Items items={items} />
      </Tree>
    </div>
  )
}

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

加载子节点

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

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

"use client"

import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
} from "@ui-sdk/react/tree"
import { ChevronRightIcon, LoaderCircleIcon, RotateCwIcon } from "lucide-react"
import * as React from "react"

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

function Items({
  items,
  loaded,
}: {
  items: Node[]
  loaded: Record<string, Node[]>
}) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value} branch={item.branch}>
      <TreeItemLabel>
        {item.branch && (
          <TreeItemIndicator>
            {(state) =>
              state.loading ? (
                <LoaderCircleIcon aria-hidden="true" />
              ) : state.failed ? (
                <RotateCwIcon aria-hidden="true" />
              ) : (
                <ChevronRightIcon aria-hidden="true" />
              )
            }
          </TreeItemIndicator>
        )}
        {item.label}
      </TreeItemLabel>
      {loaded[item.value] && (
        <TreeGroup>
          <Items items={loaded[item.value]} loaded={loaded} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

function Example() {
  const [loaded, setLoaded] = React.useState<Record<string, Node[]>>({})
  return (
    <Tree
      aria-label="Database"
      loadChildren={async (value, { signal }) => {
        const children = await fetchChildren(value, signal)
        setLoaded((loaded) => ({ ...loaded, [value]: children }))
      }}
      announcement={({ type, label }) =>
        ({
          expanded: "Expanded",
          collapsed: "Collapsed",
          loading: `Loading ${label}`,
          "load-failed": `${label} didn't load. Try again.`,
        })[type]
      }
    >
      <Items items={top} loaded={loaded} />
    </Tree>
  )
}

export { Example }
展开 users 加载它的文件。Archive 第一次尝试会失败,并显示重试图标;再次展开它就能加载。

虚拟化

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

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

"use client"

import {
  Tree,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
  visibleTreeRows,
  type TreeItemData,
} from "@ui-sdk/react/tree"
import { ChevronRightIcon } from "lucide-react"
import * as React from "react"

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 Example() {
  const scroller = React.useRef<HTMLDivElement>(null)
  const [scrollTop, setScrollTop] = React.useState(0)
  const [expanded, setExpanded] = React.useState(["folder-1"])
  const rows = React.useMemo(() => visibleTreeRows(items, expanded), [expanded])
  const start = Math.max(0, Math.floor(scrollTop / row) - 4)
  const end = Math.min(rows.length, Math.ceil((scrollTop + height) / row) + 4)
  return (
    <div
      data-slot="scroll"
      ref={scroller}
      onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
    >
      <Tree
        aria-label="Archive"
        items={items}
        expanded={expanded}
        onExpandedChange={setExpanded}
        onHighlight={(_value, { index }) => {
          const el = scroller.current
          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
          }
          setScrollTop(el.scrollTop)
        }}
        style={{ height: rows.length * row }}
      >
        {rows.slice(start, end).map(({ item, index }) => (
          <TreeItem
            key={item.value}
            value={item.value}
            style={{ top: index * row }}
          >
            <TreeItemLabel>
              {item.children && (
                <TreeItemIndicator>
                  <ChevronRightIcon aria-hidden="true" />
                </TreeItemIndicator>
              )}
              {item.label}
            </TreeItemLabel>
          </TreeItem>
        ))}
      </Tree>
    </div>
  )
}

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

在页面中查找

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

"use client"

import {
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
  type TreeItemData,
} from "@ui-sdk/react/tree"
import { ChevronRightIcon } from "lucide-react"

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 Items({ items }: { items: TreeItemData[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value}>
      <TreeItemLabel>
        {item.children && (
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        )}
        {item.label}
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

function Example() {
  return (
    <Tree aria-label="Solar system" items={items} hiddenUntilFound>
      <Items items={items} />
    </Tree>
  )
}

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

动画

分组把测量到的高度暴露为 --tree-group-height。在 data-starting-style 和 data-ending-style 之间,从这个高度过渡到零:

[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

传入值及其变更回调来控制它,或用 defaultValue、defaultExpanded 和 defaultChecked 设置起始状态。在变更回调里调用 details.cancel() 拒绝变更。状态与事件介绍了共享的绑定方式。

控制器

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

"use client"

import {
  createTreeController,
  Tree,
  TreeGroup,
  TreeItem,
  TreeItemIndicator,
  TreeItemLabel,
  type TreeItemData,
} from "@ui-sdk/react/tree"
import { ChevronRightIcon } from "lucide-react"
import * as React from "react"

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 Items({ items }: { items: TreeItemData[] }) {
  return items.map((item) => (
    <TreeItem key={item.value} value={item.value}>
      <TreeItemLabel>
        {item.children && (
          <TreeItemIndicator>
            <ChevronRightIcon aria-hidden="true" />
          </TreeItemIndicator>
        )}
        {item.label}
      </TreeItemLabel>
      {item.children && (
        <TreeGroup>
          <Items items={item.children} />
        </TreeGroup>
      )}
    </TreeItem>
  ))
}

function Example() {
  const [settings] = React.useState(() => createTreeController())
  return (
    <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}>
        <Items items={sections} />
      </Tree>
    </div>
  )
}

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

自定义渲染

每个部件都接受 render。链接示例把 TreeItemLabel 渲染成 a;标签里的链接把 Tab 顺序留给它的条目。TreeItemLabel 和 TreeItemIndicator 也接受一个接收条目状态的函数,文件路径和加载子节点示例用它来显示加载指示器。props 合并和基于状态的渲染见部件与组合。

样式

通过 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,它的状态属性列在数据属性下。

TreeItem

变量内容
--tree-levelThe item's depth, 1 for a top-level item. Indent a flat tree with it.

TreeGroup

变量内容
--tree-group-heightThe group's content height in pixels while it animates, auto once expanded and 0px while collapsed.

数据属性

TreeItem

[data-slot="tree-item"]

属性含义
data-level12The item's depth, from 1 at the top level. Also in the --tree-level variable.
data-branchPresent on a branch: an item with children, or with branch set.
data-expandedPresent while a branch is expanded.
data-indeterminatePresent while only some of a branch is checked, with checkable.
data-selectedPresent while the item is selected.
data-currentPresent on the item for the current page, from current.
data-checkedPresent while the item's checkbox is checked, with checkable.
data-disabledPresent when the item, or the whole tree, is disabled.
data-uncheckedPresent while the item's checkbox is unchecked, with checkable.
data-loadingPresent while loadChildren loads the branch's children.
data-failedPresent after the branch's children failed to load, until it loads again.
data-pendingPresent while the item's onAction Promise hasn't settled.

TreeItemLabel

[data-slot="tree-label"]

属性含义
data-level12The item's depth, from 1 at the top level. Also in the --tree-level variable.
data-branchPresent on a branch: an item with children, or with branch set.
data-expandedPresent while a branch is expanded.
data-selectedPresent while the item is selected.
data-currentPresent on the item for the current page, from current.
data-disabledPresent when the item, or the whole tree, is disabled.
data-loadingPresent while loadChildren loads the branch's children.
data-failedPresent after the branch's children failed to load, until it loads again.
data-pendingPresent while the item's onAction Promise hasn't settled.

TreeItemIndicator

[data-slot="tree-indicator"]

属性含义
data-level1The item's depth, from 1 at the top level. Also in the --tree-level variable.
data-branchPresent on a branch: an item with children, or with branch set.
data-expandedPresent while a branch is expanded.
data-loadingPresent while loadChildren loads the branch's children.
data-failedPresent after the branch's children failed to load, until it loads again.
data-pendingPresent while the item's onAction Promise hasn't settled.

TreeItemCheckbox

[data-slot="tree-checkbox"]

属性含义
data-indeterminatePresent while only some of a branch is checked, with checkable.
data-checkedPresent while the item's checkbox is checked, with checkable.
data-uncheckedPresent while the item's checkbox is unchecked, with checkable.

TreeGroup

[data-slot="tree-group"]

属性含义
data-openPresent while the group's branch is expanded.
data-closedPresent 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

valuestring
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 里的每个条目:

valuestring
Identifies the item. Unique in the tree.
labelstring
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) 为扁平列表返回的每一行:

itemTreeItemData
The object from your data this row shows, the same one you passed in, children included.
parentstring | null
The value of the item it's nested in, or null at the top level.
levelnumber
Its depth, 1 at the top level.
indexnumber
Its place among the rows that show, from 0, for a virtualized list.

状态

每个部件的渲染函数、基于状态的类名和槽位会收到什么。

Tree:

modeTreeMode
How many items can be selected.
checkableboolean
Whether items have checkboxes.
disabledboolean
Whether the whole tree is disabled, by its disabled option or a disabled fieldset around it.

TreeItem,以及它的 TreeItemLabel、TreeItemIndicator 和 TreeItemCheckbox:

expandedboolean
Whether it's a branch that's expanded.
selectedboolean
Whether its value is in the tree's value. Separate from checked, which its checkbox sets.
checkedTreeCheckedState
Its checkbox: checked, unchecked or "indeterminate". False without checkable.
disabledboolean
Whether it can't be selected, checked, expanded or run.
branchboolean
Whether it has children, or can load them.
levelnumber
Its depth, 1 at the top level.
currentboolean
Whether it's the current page's item.
loadingboolean
Whether its children are loading.
failedboolean
Whether loading its children failed.
pendingboolean
Whether its onAction is still running.

TreeGroup:

expandedboolean
Whether its branch is expanded.
levelnumber
The depth of the items in it.

原因

分支为什么展开或折叠:

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
trigger-pressMouseEvent | 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-navigationKeyboardEvent
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-pageEvent
The browser's find in page matched hidden content.
imperativenone
A controller or api call.

选择为什么变化:

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
list-navigationKeyboardEvent
Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
imperativenone
A controller or api call.

以及复选框为什么变化:

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
imperativenone
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 树视图模式。条目的角色是 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.

运行于 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.

运行于 React、Vue 和 web components。