VirtualTree 虚拟化树
面向超大层级数据的虚拟化树,只构建视口内的可见节点,同时支持展开、勾选、过滤、键盘导航和懒加载。
何时使用
- 节点数达到数千、数万甚至更多,需要在固定高度视口中高效浏览时。
- 需要树形勾选、半选联动、当前节点、过滤高亮或按键定位时。
- 数据量较小或需要拖拽排序、连接线等完整普通树能力时用 Tree 树形控件;表单内选择层级值时用 TreeSelect 树选择。
在线体验
示例包含十万节点、可勾选半选联动、键盘导航、过滤匹配路径、懒加载和自定义节点内容。
基本用法
下面代码放在应用的页面文件中;完整的 main 和窗口初始化见 打开自绘窗口。节点的 Key 在整棵树中必须唯一。
import (
"github.com/tangoui/tango/ui"
)
var nodes = []ui.TreeNode{
{Key: "docs", Title: "文档", Children: []ui.TreeNode{
{Key: "guide", Title: "指南"},
{Key: "api", Title: "API"},
}},
{Key: "examples", Title: "示例", IsLeaf: true},
}
var expanded = []string{"docs"}
func page(c *ui.Context) {
ui.VirtualTree(c, nodes).Expanded(&expanded).Height(240).Show()
}VirtualTree(c, nodes) 会把展开后的可见节点展平,并只构建视口附近的行。用 Expanded、Current、Checkable 把树状态绑定到应用变量;不绑定时对应状态留在组件自己的状态中。
常见用法
以下片段沿用基本用法里的 nodes,省略了 import。
勾选与半选
Checkable(&checked) 显示复选框并绑定完整勾选键。默认父子联动,部分子节点选中时父节点出现在 HalfChecked() 中;CheckStrictly 让每个节点独立。
var checked = []string{"guide"}
func checkableTree(c *ui.Context) {
tree := ui.VirtualTree(c, nodes).Expanded(&expanded).
Checkable(&checked).Height(240).Show()
if tree.CheckChanged() {
ui.Text(c, fmt.Sprintf("半选:%v", tree.HalfChecked())).Tertiary()
}
}搜索过滤与自定义节点
Filter 默认大小写不敏感地匹配标题,同时保留匹配节点的祖先并展开路径。FilterMethod 可以改为匹配业务字段,NodeRender 则完全接管行内容。
var query string
func searchableTree(c *ui.Context) {
ui.Input(c, &query).Placeholder("过滤节点")
ui.VirtualTree(c, nodes).Filter(query).FilterMethod(func(q string, n *ui.TreeNode) bool {
return strings.Contains(strings.ToLower(n.Title), strings.ToLower(q))
}).NodeRender(func(n *ui.TreeNode, depth int) {
ui.Text(c, fmt.Sprintf("%*s%s", depth*2, "", n.Title))
}).Height(260).Show()
}异步懒加载
展开没有子节点且没有 IsLeaf 标记的节点时,组件会持续调用 LoadData 回调;返回 true 表示仍在加载,返回 false 表示本次加载完成。数据到达后把子节点写回原树。
var lazyNodes = []ui.TreeNode{{Key: "remote", Title: "远程目录"}}
var loadingTicks = map[string]int{}
func lazyTree(c *ui.Context) {
ui.VirtualTree(c, lazyNodes).LoadData(func(key string) bool {
loadingTicks[key]++
if loadingTicks[key] < 3 {
return true
}
for i := range lazyNodes {
if lazyNodes[i].Key == key && len(lazyNodes[i].Children) == 0 {
lazyNodes[i].Children = []ui.TreeNode{
{Key: key + "-a", Title: "子节点 A", IsLeaf: true},
{Key: key + "-b", Title: "子节点 B", IsLeaf: true},
}
}
}
return false
}).Height(220).Show()
}当前节点、点击和按键定位
Current 绑定键盘当前节点;NodeClicked 返回本次 Show 中被点击的节点键。ScrollToKey 会展开目标的祖先并把目标滚动到视口内,适合从外部搜索结果跳转。
var current = "guide"
var targetKey = "api"
func navigableTree(c *ui.Context) {
tree := ui.VirtualTree(c, nodes).Current(¤t).Height(240)
if ui.Button(c, "定位 API").Clicked() {
tree.ScrollToKey(targetKey)
}
tree.Show()
if key, ok := tree.NodeClicked(); ok {
ui.Text(c, "点击:"+key).Tertiary()
}
}原地更新节点
组件按顶层切片的身份、长度和数据版本缓存索引。原地修改键、子节点或影响过滤的字段后,递增 DataVersion 以重建索引和过滤结果。
var treeVersion int
func updatedTree(c *ui.Context) {
ui.VirtualTree(c, nodes).DataVersion(treeVersion).Height(240).Show()
}主题与样式
VirtualTree 复用 Tree 的节点令牌(行高、缩进、选中和过滤高亮),三套主题分别对齐 Ant Design、Element Plus 和 shadcn 的树视觉。ConfigProvider.Defaults("VirtualTree", ...) 支持 "checkStrictly"、"expandOnClickNode" 和 "checkOnClickNode";实例方法 CheckStrictly、ExpandOnClick、CheckOnClick 可覆盖默认值。
注意事项
- Key 唯一:
TreeNode.Key必须在整棵树中唯一;展开、勾选、当前节点和懒加载都以它作为身份。 - 状态放在哪:需要被页面其他区域读取的状态绑定到
Expanded、Checkable、Current的切片或字符串;筛选关键字放在页面变量里。 - 回调时机:
CheckChanged、ExpandChanged和CurrentChanged要在Show返回后读取;Range返回本帧构建行的半开区间。 - 性能:
Height决定虚拟视口;节点总数可以很大,但展开后的可见索引、过滤结果和行回调仍应避免重复做昂贵工作。 - 键盘与无障碍:整棵树是一个 Tab 停靠点。↑/↓、PageUp/PageDown、Home/End 移动,←/→ 收起或展开,Enter 设置当前节点,空格在可勾选时切换。需要无障碍名称时应给外层区域提供清晰标题。
- RTL:缩进、展开方向和节点布局遵循当前 RTL 设置。
示例代码
以下是上方在线演示运行的 Go 源码(来自官方 gallery),点击标题展开。函数接收的 c *ui.Context 由窗口的 UI 循环每帧传入,接入方式见 Go GUI 入门。
API
签名与说明由 site/tools/compdoc 从 Go 源码和文档注释提取;点击名称跳到 Go API 参考 的对应条目。
入口函数
ui.VirtualTree
func VirtualTree(c *Context, nodes []TreeNode) *VirtualTreeWVirtualTree starts a virtualized tree over nodes (keys unique in the whole tree); configure with modifiers and call Show.
Keyboard (the tree is one Tab stop): Up/Down/PageUp/PageDown/Home/End move the cursor row, Right expands or enters the first child, Left collapses or returns to the parent, Enter makes the row current, Space checks it when Checkable.
ui.VirtualTree(c, nodes).Checkable(&checked).Height(400).Show()
返回 *VirtualTreeW,可链式调用的方法见 VirtualTreeW 方法。
VirtualTreeW 方法
ui.VirtualTreeW:VirtualTreeW is a virtualized tree. Configure it with modifiers and call Show.
| 方法 | 说明 | 签名 |
|---|---|---|
Accordion | Accordion keeps one node expanded per level: expanding a node collapses its expanded siblings (Element accordion). | Accordion() *VirtualTreeW |
CheckChanged | CheckChanged / ExpandChanged / CurrentChanged report changes in Show. | CheckChanged() bool |
CheckOnClick | CheckOnClick toggles the check box when a row is clicked. | CheckOnClick() *VirtualTreeW |
CheckOnClickLeaf | CheckOnClickLeaf toggles the check box when a leaf row is clicked (Element check-on-click-leaf; off by default, as antd selects instead). | CheckOnClickLeaf(on bool) *VirtualTreeW |
CheckStrictly | CheckStrictly makes parent and child check states independent. | CheckStrictly() *VirtualTreeW |
Checkable | Checkable shows check boxes bound to checked keys (fully checked keys, parents included; nil keeps them inside the tree). | Checkable(checked *[]string) *VirtualTreeW |
Current | Current binds the current (highlighted) node key. | Current(key *string) *VirtualTreeW |
CurrentChanged | CurrentChanged() bool | |
DataVersion | DataVersion tells the tree that nodes were modified in place (the index is keyed by the slice identity and this number). | DataVersion(v int) *VirtualTreeW |
EmptyText | EmptyText shows s instead of the empty illustration when no row is shown (Element empty-text); the Element theme shows Locale.NoData (TreeToken.ShowEmptyText). | EmptyText(s string) *VirtualTreeW |
ExpandChanged | ExpandChanged() bool | |
ExpandOnClick | ExpandOnClick toggles expansion when a row is clicked (Element's expand-on-click-node; on by default with the Element theme). | ExpandOnClick(on bool) *VirtualTreeW |
Expanded | Expanded binds the expanded keys to the app. | Expanded(keys *[]string) *VirtualTreeW |
Filter | Filter shows only nodes matching query (case-insensitive title match) and their ancestors, expanding the ancestors when the query changes. | Filter(query string) *VirtualTreeW |
FilterMethod | FilterMethod replaces the title match used by Filter. | FilterMethod(fn func(query string, n *TreeNode) bool) *VirtualTreeW |
HalfChecked | HalfChecked returns the half-checked keys (after Show). | HalfChecked() []string |
Height | Height sets the viewport height (default 200, Element's default). | Height(px float32) *VirtualTreeW |
ID | ID returns the scroll viewport's ID (after Show). | ID() ID |
LoadData | LoadData enables lazy loading: expanding a non-leaf node without children calls fn(key) every frame until it returns false (still loading = true). | LoadData(fn func(key string) bool) *VirtualTreeW |
NodeClicked | NodeClicked returns the key of the row clicked in Show. | NodeClicked() (string, bool) |
NodeRender | NodeRender builds each row's content with fn instead of the title. | NodeRender(fn func(n *TreeNode, depth int)) *VirtualTreeW |
Range | Range returns the rows [first, end) built by Show. | Range() (first, end int) |
ScrollToKey | ScrollToKey expands the ancestors of key and scrolls its row into view. | ScrollToKey(key string) *VirtualTreeW |
Show | Show builds the tree. | Show() *VirtualTreeW |
VisibleCount | VisibleCount returns the number of rows (expanded and not filtered out). | VisibleCount() int |
TreeNode 参数类型
ui.TreeNode:TreeNode is one node of a Tree. Keys must be unique in the whole tree.
| 字段 | 说明 | 类型 |
|---|---|---|
Key | string | |
Title | string | |
Children | []TreeNode | |
IsLeaf | never expandable (relevant with LoadData) | bool |
Disabled | bool | |
DisableCheckbox | bool | |
Icon | shown with ShowIcon; nil uses folder/file | *icon.Icon |