Tree
树:展开、选择、标记、搜索、异步加载和键盘。
何时使用
树显示文件夹、文档部分或组织层次结构。可以展开分支,可以选择行,并且可以用复选框标记节点。对于紧凑输入字段内的树,请使用 TreeSelect。
使用唯一的持久键传递嵌套的 treeData。key 标识整个树中的节点,而不仅仅是其邻居中的节点;title 负责签名。
CSS 树前缀 显示全局 ConfigProvider.prefixCls 和本地 prefixCls,无需重置状态。节点、切换器、复选框和线使用树前缀。 DOM、ARIA ID、选定的键和未完成的加载都会被保留。 TreeSelect 有自己的树适配器。
显示、选择和标记
expandedKeys、selectedKeys 和 checkedKeys 是三个独立的状态。更改其中一项不应取代其他两项。对于托管树,通过适当的回调接受新密钥。
| 问题 | 设置 | 示例 |
|---|---|---|
| 显示嵌套节点 | treeData、defaultExpandedKeys |
普通树 |
| 外部管理状态 | expandedKeys、selectedKeys、checkedKeys |
管理树 |
| 选择多行 | multiple、onSelect |
普通树 |
| 比较复选框规则 | checkable, checkStrictly |
相关标记和独立标记 |
| 加载子节点 | loadData, loadedKeys |
加载时出错并重试 |
defaultExpandedKeys、defaultSelectedKeys 和 defaultCheckedKeys 在创建树时被读取。 defaultExpandAll 也适用于初始数据集。对于稍后到达的数据,接收后管理 expandedKeys 或创建Tree。
checkable 启用复选框。默认情况下,标记在父级和子级之间传播,不完整的分支会收到部分标记。 checkStrictly 禁用连接:onCheck 返回一个 checked/halfChecked 对象。disabled 节点会停止通过自身传播标记。 selectable 和 disableCheckbox 分别控制行选择和复选框可用性。
加载并搜索
loadData 接收一个 TreeEventNode 并返回一个 Promise。对于卸载的分支,设置 isLeaf=false;响应后,将 children 添加到 treeData 并完成 Promise。 loadedKeys 存储已完成下载的密钥,onLoad 报告其更新。在托管场景中,接受新的 loadedKeys,以便加载状态与数据匹配。
异步示例 显示错误并重新打开。错误消息和请求属于应用程序;离开页面时,释放您的计时器和资源。
filterTreeNode 突出显示匹配的节点而不是删除其他行。 搜索单独计算 expandedKeys 匹配的父级并通过 titleRender 绘制标记。使用您自己的过滤器,保存必要的祖先和稳定密钥。
设计和键盘
showLine 绘制连接,showIcon 包含图标。 titleRender、icon、switcherIcon 和 switcherLoadingIcon 接受 Svelte 片段; TreeEventNode 包含节点状态,包括展开、选择和 loading。 示例图标 无需更改按键即可更改视图。
blockNode 拉伸行;height 定义虚拟视口。virtual=false 时,所有展开行保留在 DOM 中并使用原生滚动。API覆盖范围 列出可用设置。
拖放节点 演示 Tree/DirectoryTree 的 draggable、allowDrop 和 onDrop,包括 RTL 和虚拟滚动。数据由应用移动。dropToGap=false 表示移入节点内部;间隙放置时,从 info.dropPosition 减去 node.pos 的最后一个索引,得到 -1 或 1。dragNodesKeys 包含源节点和所有后代的键。nodeDraggable=false 禁用该行的拖动和 drop;icon=false 仅隐藏拖动手柄。disabled 禁止开始拖动,但放置目标需要另用 allowDrop 限制。onDragEnter 提供延迟展开前的键;800 ms 后 onExpand 接收新的键。
树展开动画 对比默认 collapse、自定义 CSS 阶段和 motion=false。null/undefined 启用默认过渡;start/active 回调返回 CSS 字符串,prepare 可以返回 Promise。没有 CSS 事件时,motionDeadline 结束过渡。库遵循减少动态效果设置;theme.token.motion=false 跳过 CSS 阶段,但保留 prepare。同时修改多个 expandedKeys 时不执行过渡。虚拟模式下 motion 组受窗口限制;拖动结束、替换数据和卸载会取消过时的回调。
根 class/style 和各个节点的 class/style 可用。树组件设计令牌(design tokens)反应式操作和更新;DirectoryTree 令牌用于文件树的已选行。 示例主题 在更改设计时保留选择。
重点仍然是 role=tree,活动节点通过 aria-activedescendant 传递。箭头移动它并打开/折叠分支,Home/End 移动到边缘。 Enter 展开分支或选择叶子,Space 更改标记或选择。 键盘示例 显示 activeKey 和焦点操作。 bind:nativeElement 在挂载后返回外部根。
Tree 和 DirectoryTree 通过 tabIndex 设置焦点顺序。示例中的 tabIndex={-1} 让 Tab 键跳过树,按钮则通过 focus() 将焦点移入树中。onFocus 和 onBlur 报告焦点变化。onKeyDown 在树处理按键后收到原生事件。onMouseDown 和 onContextMenu 接收树上的鼠标事件。
展开、文件与数据路径
标题展开 支持 expandAction=false、click 和 doubleClick。Ctrl/Meta/Shift 只改变选择;展开按钮和键盘操作相互独立。
文件树 使用 DirectoryTree。默认值为 showIcon=true、blockNode=true 和 expandAction="click"。启用 multiple 时,普通点击选择一行,Ctrl/Meta 切换键,Shift 选择可见行的范围。再次点击不会清除选择。
节点图标 展示 TreeDataNode.switcherIcon 和 showLine.showLeafIcon snippet。节点自身的图标覆盖公共展开图标和 loading 指示器;onMouseEnter/onMouseLeave 接收 event 和当前 TreeEventNode,包括 disabled 节点。
数据路径 使用 createTree(dataOrGetter, config).getPath(key),无需 DOM ref。getPath 返回从根到节点的 TreeDataEntity[];每个 entity 包含 node、nodes、key、index、pos、level、parent 和 children。未知键返回空数组。响应式更新需要传入数据 getter 和 config.fieldNames getter,并替换数组和 fieldNames 的引用。模型、Tree 和 DirectoryTree 支持相同的 fieldNames 映射;无需转换原始 payload。模型支持 SSR,不创建 DOM,也不提供 scrollTo。
数据模式与 semantic slots
类型化模式 通过 treeData 和 fieldNames 传入原始记录,映射 key/title/children。fieldNames 中的空字符串使用标准字段名。TreeProps<Data>、TreeEventNode<Data> 和 TreeCheckInfo<Data> 保留 payload 类型;TreeFieldDataNode<Payload, ChildFieldName> 描述递归数据。事件节点的状态和 canonical key 覆盖 payload 中的同名字段,而 selectedNodes/checkedNodes 包含原始记录。 Node.selected 表示选择之前的状态;info.selected 报告操作结果。
TreeTitleContent<Data> 支持文本、数字、嵌套数组和接收原始记录的 snippet。boolean、null 和 undefined 不输出内容;缺失 title 时显示 "---"。标题字段中的 snippet 优先于 titleRender。对象类型的标题请使用 titleRender:对象不会自动转换为文本。
Semantic slots 为 root、item、itemIcon、itemTitle 和 itemSwitcher 提供 classNames/styles。Record 或接收 props 的 callback 返回类名或 CSS 字符串;callback 只计算样式,不应改变状态。ConfigProvider.tree 应用于 Tree 和 DirectoryTree,但不影响 TreeSelect 的内部树。局部类名与 provider 类名累积;CSS 顺序为 provider styles、root 的 provider style、局部 styles,最后是 root 的普通 style。节点的 class/style 保留;semantic item style 位于 node.style 之后。
嵌套 ConfigProvider 的 tree=undefined 继承配置;tree={} 替换整个配置对象。样式变化保留选择、DOM 和正在进行的加载。普通 style 仍作用于外部根节点,而非内部列表。
虚拟化与滚动
虚拟树 在 Tree 和 DirectoryTree 中通过 fieldNames 展示 1000 个文件。DOM 只挂载窗口中的行,而 selectedKeys 属于完整模型。未设置 height 或 height=0 时,所有展开行无高度限制地渲染。virtual=undefined 继承 ConfigProvider.virtual;未提供全局值时,Tree 启用虚拟化。virtual=false 保留全部行并使用原生滚动。
itemHeight 覆盖来自 Tree 令牌的初始估计;itemHeight=0 关闭窗口。挂载后测量实际行高及 margins,测量结果按键保留到卸载。SSR 使用初始估计,不进行 DOM 测量、加载或计时。初始展开分支的 loadData 在其进入挂载窗口时开始。
scrollWidth 定义虚拟内容宽度。滚轮、Shift+wheel、触摸和滚动条拖动支持两个轴及 RTL。示例在虚拟模式下展示二维坐标。TreeRef.scrollTo 接收数字、{top,left} 或 {key,align,offset} 或 {index,align,offset}。align 支持 top/bottom/auto。RTL 中的 left 也是非负逻辑位置。offset 是数字或纯 TreeScrollOffset 函数;getSize(startKey,endKey?) 返回测量/估计的 top/bottom。未知 endKey 返回 bottom=undefined;NaN/Infinity offset 视为零。
scrollTo 不选择节点。未知 key 保持位置不变;null/undefined 显示滚动条。后发请求取代先前请求。itemScrollOffset 用于活动节点的自动滚动;onScroll 接收 holder 事件,bind:nativeElement 仍指向外部 root。卸载时 ref 清除,已保存的 TreeRef 安全地停止执行操作。
滚动到嵌套节点 使用 createTree.getPath 查找祖先。调用方更新 expandedKeys,等待 tick 后调用 scrollTo。Key 请求中的 autoExpand 只在非受控模式下添加目标键,不展开祖先,也不调用 onExpand。controlled 树应显式更新 expandedKeys。
示例
将文件拖到另一行或行间。onDrop 处理器更新 treeData;locked 不能作为目标,LICENSE 不能拖动。
拖放节点
Tree 和 DirectoryTree:移动数据、allowDrop、自定义手柄、RTL 和虚拟窗口。
Drag.svelte<script lang="ts"> import { Button, Checkbox, ConfigProvider, DirectoryTree, Tree, type TreeDataNode, type TreeDropInfo, type TreeDropPosition, type TreeKey } from '@woodger/antd'; import { moveTreeNode } from './drop-tree'; function initial(): TreeDataNode[] { return [ { key: 'components', title: 'components', children: [ { key: 'button', title: 'Button.svelte', isLeaf: true }, { key: 'input', title: 'Input.svelte', isLeaf: true } ] }, { key: 'guides', title: 'guides', children: [{ key: 'start', title: 'start.md', isLeaf: true }] }, { key: 'locked', title: 'locked', disabled: true, children: [{ key: 'license', title: 'LICENSE', isLeaf: true }] } ]; } let data = $state<readonly TreeDataNode[]>(initial()); let expanded = $state<TreeKey[]>(['components', 'guides', 'locked']); let directory = $state(false); let rtl = $state(false); let virtual = $state(false); let inside = $state(true); let handle = $state(true); let lastDrop = $state('—'); const Component = $derived(directory ? DirectoryTree : Tree); function drop(info: TreeDropInfo) { const position = info.dropToGap ? info.dropPosition - Number(info.node.pos.split('-').at(-1)) : 0; data = moveTreeNode(data, info.dragNode.key, info.node.key, position as TreeDropPosition); lastDrop = `${info.dragNode.key} → ${info.node.key} (${position})`; } </script> {#snippet dragHandle()}<span aria-hidden="true">⠿</span>{/snippet} <div class="controls"> <Checkbox bind:checked={directory}>DirectoryTree</Checkbox> <Checkbox bind:checked={rtl}>RTL</Checkbox> <Checkbox bind:checked={virtual}>{("拖放虚拟窗口")}</Checkbox> <Checkbox bind:checked={inside}>{("允许移入节点内部")}</Checkbox> <Checkbox bind:checked={handle}>{("显示拖动手柄")}</Checkbox> <Button onclick={() => { data = initial(); expanded = ['components', 'guides', 'locked']; lastDrop = '—'; }}>{("重置树顺序")}</Button> </div> <ConfigProvider direction={rtl ? 'rtl' : 'ltr'}> <Component treeData={data} expandedKeys={expanded} onExpand={keys => { expanded = keys; }} blockNode draggable={{ icon: handle ? dragHandle : false, nodeDraggable: node => node.key !== 'license' }} allowDrop={({ dropNode, dropPosition }) => !dropNode.disabled && (inside || dropPosition !== 0)} onDrop={drop} height={virtual ? 160 : undefined} virtual={virtual} motion={false} aria-label={("可拖放树")} /> </ConfigProvider> <output aria-label={("上一次树拖放")}>{lastDrop}</output> <p> {("将文件拖到另一行或行间。onDrop 处理器更新 treeData;locked 不能作为目标,LICENSE 不能拖动。")} </p> <style>.controls { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; } output { display: block; margin-top: 12px; overflow-wrap: anywhere; } p { line-height: 1.6; }</style>drop-tree.tsimport type { TreeDataNode, TreeDropPosition, TreeKey } from '@woodger/antd'; export function moveTreeNode( data: readonly TreeDataNode[], dragKey: TreeKey, targetKey: TreeKey, position: TreeDropPosition ): readonly TreeDataNode[] { function find(nodes: readonly TreeDataNode[], key: TreeKey): TreeDataNode | undefined { for (const node of nodes) { if (node.key === key) { return node; } const nested = find(node.children ?? [], key); if (nested) { return nested; } } } const source = find(data, dragKey); if (!source || !find(data, targetKey) || find([source], targetKey) || ![-1, 0, 1].includes(position)) { return data; } function remove(nodes: readonly TreeDataNode[]): TreeDataNode[] { return nodes.filter(node => node.key !== dragKey).map( node => node.children ? { ...node, children: remove(node.children) } : node ); } function insert(nodes: readonly TreeDataNode[]): TreeDataNode[] { return nodes.flatMap(node => { if (node.key === targetKey) { if (position === 0) { return [{ ...node, isLeaf: false, children: [ ...(node.children ?? []), source! ] }]; } return position === -1 ? [source!, node] : [node, source!]; } return [ node.children ? { ...node, children: insert(node.children) } : node ]; }); } return insert(remove(data)); }
默认启用 collapse 动画。自定义对象定义 CSS 阶段和回调;motion=false 禁用过渡。库遵循减少动态效果设置。
树展开动画
默认 collapse、自定义阶段、禁用 motion 和保留相邻输入。
<script lang="ts">
import {
Button,
Checkbox,
DirectoryTree,
Input,
Tree,
type TreeKey,
type TreeMotionConfig
} from '@woodger/antd';
const data = [{
key: 'src', title: 'src', children: [
{ key: 'app', title: 'App.svelte', isLeaf: true },
{ key: 'layout', title: '+layout.svelte', isLeaf: true },
{ key: 'page', title: '+page.svelte', isLeaf: true }
]
}];
let expanded = $state<TreeKey[]>([]);
let directory = $state(false);
let enabled = $state(true);
let custom = $state(false);
let completed = $state(0);
let draft = $state('Svelte');
const Component = $derived(directory ? DirectoryTree : Tree);
const collapsed = () => `
height: 0px;
opacity: 0;
`;
const customMotion: TreeMotionConfig = {
motionName: 'site-tree-motion', motionDeadline: 500,
onAppearStart: collapsed,
onAppearActive: node => `
height: ${node.scrollHeight}px;
opacity: 1;
`,
onLeaveStart: node => `
height: ${node.offsetHeight}px;
opacity: 1;
`,
onLeaveActive: collapsed,
onAppearEnd: (_node, event) => {
if ('deadline' in event || 'propertyName' in event && event.propertyName === 'height') {
completed += 1;
return true;
} return false;
},
onLeaveEnd: (_node, event) => {
if ('deadline' in event || 'propertyName' in event && event.propertyName === 'height') {
completed += 1;
return true;
} return false;
}
};
</script>
<div class="controls">
<Checkbox bind:checked={directory}>DirectoryTree</Checkbox>
<Checkbox bind:checked={enabled}>{("Tree 分支动画")}</Checkbox>
<Checkbox bind:checked={custom}>{("自定义 motion 阶段")}</Checkbox>
<Button onclick={() => { expanded = expanded.includes('src') ? [] : ['src']; }}>
{("展开或折叠分支")}
</Button>
</div>
<Component treeData={data} expandedKeys={expanded} onExpand={keys => { expanded = keys; }}
motion={enabled ? custom ? customMotion : undefined : false} aria-label={("带动画的树")} />
<div
class="draft"
><Input
bind:value={draft}
aria-label={("树旁的草稿")}
/></div>
<output aria-label={("已完成的 Tree 阶段")}>{completed}</output>
<p>
{("默认启用 collapse 动画。自定义对象定义 CSS 阶段和回调;motion=false 禁用过渡。库遵循减少动态效果设置。")}
</p>
<style>
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 16px;
}
.draft {
max-width: 280px;
margin-block: 12px;
}
:global(.site-tree-motion-appear-active),
:global(.site-tree-motion-leave-active) {
overflow: hidden;
transition: height .22s ease, opacity .22s ease;
}
@media (prefers-reduced-motion: reduce) {
:global(.site-tree-motion-appear-active),
:global(.site-tree-motion-leave-active) {
transition: none;
}
}
p { line-height: 1.6; }
</style>
普通树
初始键、disabled 和 checkable。
Basic.svelte<script lang="ts"> import { Tree } from '@woodger/antd'; import { treeData } from './data'; </script> <Tree {treeData} checkable defaultExpandedKeys={['project', 'docs']} defaultSelectedKeys={['button']} aria-label={("普通树")} />data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "项目", children: [ { key: 'docs', title: "文档", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "示例", children: [{ key: 'forms', title: "表格", isLeaf: true }] }, { key: 'archive', title: "档案", disabled: true, children: [{ key: 'archived', title: "文档", isLeaf: true }] } ] }];
管理树
独立的 expandedKeys 和 selectedKeys。
Controlled.svelte<script lang="ts"> import { Button, Tree, type TreeKey } from '@woodger/antd'; import { treeData } from './data'; let expanded = $state<TreeKey[]>(['project', 'docs']); let selected = $state<TreeKey[]>(['button']); </script> <style> .example { display: grid; gap: 20px; } </style> <div class="example"> <Tree {treeData} multiple expandedKeys={expanded} selectedKeys={selected} onExpand={keys => { expanded = keys; }} onSelect={keys => { selected = keys; }} aria-label={("管理树")} /> <Button onclick={() => { expanded = ['project']; selected = []; }}> {("重置托管树")} </Button> <output aria-label={("选择托管树")} >{("已选择: ")}{(selected.map(String).join(', ') || '—')}</output> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "项目", children: [ { key: 'docs', title: "文档", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "示例", children: [{ key: 'forms', title: "表格", isLeaf: true }] }, { key: 'archive', title: "档案", disabled: true, children: [{ key: 'archived', title: "文档", isLeaf: true }] } ] }];
相关标记和独立标记
传导、局部状态和 checkStrictly。
Checks.svelte<script lang="ts"> import { Checkbox, Tree, type TreeKey, type TreeCheckedKeys } from '@woodger/antd'; import { treeData } from './data'; let strict = $state(false); let checked = $state<TreeKey[] | TreeCheckedKeys>([]); let keys = $derived('checked' in checked ? checked.checked : checked); </script> <style> .example { display: grid; gap: 20px; } </style> <div class="example"> <Checkbox checked={strict} onCheckedChange={next => { strict = next; checked = []; }}> {("独立树标")} </Checkbox> <Tree {treeData} checkable checkStrictly={strict} checkedKeys={checked} onCheck={next => { checked = next; }} defaultExpandAll aria-label={("标记树")} /> <output aria-label={("标记树键")}>{("著名的: ")}{(keys .map(String).join(', ') || '—')}</output> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "项目", children: [ { key: 'docs', title: "文档", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "示例", children: [{ key: 'forms', title: "表格", isLeaf: true }] }, { key: 'archive', title: "档案", disabled: true, children: [{ key: 'archived', title: "文档", isLeaf: true }] } ] }];
加载时出错并重试
Promise loadData、loadedKeys 并在重置时清除。
Async.svelte<script lang="ts"> import { Button } from '@woodger/antd'; import LazyTree from './LazyTree.svelte'; let revision = $state(0); </script> <style> .example { display: grid; gap: 20px; } </style> <div class="example"> <Button onclick={() => { revision++; }}> {("重置树加载")} </Button> {#key revision}<LazyTree />{/key} </div>LazyTree.svelte<script lang="ts"> import { onDestroy } from 'svelte'; import { Alert, Checkbox, Tree, type TreeDataNode, type TreeKey, type TreeEventNode } from '@woodger/antd'; let nodes = $state.raw<TreeDataNode[]>([{ key: 'remote', title: "已删除的部分", isLeaf: false }]); let loaded = $state<TreeKey[]>([]); let fail = $state(false); let busy = $state(false); let error = $state(''); let active = true; let timer: ReturnType<typeof setTimeout> | undefined; let settle: (() => void) | undefined; function loadData(node: TreeEventNode): Promise<void> { const failed = fail; busy = true; error = ''; return new Promise((resolve, reject) => { settle = resolve; timer = setTimeout(() => { timer = undefined; settle = undefined; if (!active) { resolve(); return; } busy = false; if (failed) { error = ("无法加载分区。取消选中错误并再次展开分支。"); reject(new Error((error))); } else { nodes = nodes.map( item => item.key === node.key ? { ...item, children: [ { key: 'remote-form', title: "服务器上的表单", isLeaf: true }, { key: 'remote-table', title: "服务器上的表", isLeaf: true } ] } : item ); resolve(); } }, 400); }); } onDestroy(() => { active = false; clearTimeout(timer); settle?.(); }); </script> <style> .example { display: grid; gap: 20px; } </style> <div class="example"> <Checkbox bind:checked={fail} disabled={busy}> {("树加载错误")} </Checkbox> <Tree treeData={nodes} {loadData} loadedKeys={loaded} onLoad={keys => { if (active) loaded = keys; }} aria-label={("加载树分区")} /> {#if error}<Alert type="error" title={("树加载错误")} description={error} showIcon />{/if} <output aria-label={("加载树键")} >{("已上传: ")}{(loaded.map(String).join(', ') || '—')}</output> </div>
搜索和突出显示
搜查发现了父母; filterTreeNode 突出显示匹配项。
Search.svelte<script lang="ts"> import { Input, Tree, type TreeDataNode, type TreeKey } from '@woodger/antd'; import { treeData } from './data'; let query = $state(''); let expanded = $state<TreeKey[]>(['project']); function search(value: string | undefined) { query = value ?? ''; const found = new Set<TreeKey>(); function visit(nodes: readonly TreeDataNode[], ancestors: TreeKey[]) { for (const node of nodes) { if (query && String(node.title).toLocaleLowerCase().includes(query.toLocaleLowerCase())) { for (const key of ancestors) found.add(key); } if (node.children) visit(node.children, [...ancestors, node.key]); } } visit(treeData, []); expanded = query ? [...found] : ['project']; } </script> <style> .example { display: grid; gap: 20px; } mark { color: var(--ant-color-text); background: var(--ant-color-warning-bg); } </style> {#snippet title(node: TreeDataNode)} {@const text = String(node.title ?? node.key)} {@const index = query ? text.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) : -1} {#if index < 0} {(text)} {:else}{(text.slice(0, index))}<mark> {(text.slice(index, index + query.length))} </mark>{(text.slice(index + query.length))}{/if} {/snippet} <div class="example" ><Input aria-label={("搜索树部分")} value={query} onValueChange={search} allowClear /> <Tree {treeData} expandedKeys={expanded} onExpand={keys => { expanded = keys; }} titleRender={title} filterTreeNode={node => Boolean(query && String(node.title).toLocaleLowerCase().includes( query.toLocaleLowerCase() ))} aria-label={("树搜索")} /></div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "项目", children: [ { key: 'docs', title: "文档", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "示例", children: [{ key: 'forms', title: "表格", isLeaf: true }] }, { key: 'archive', title: "档案", disabled: true, children: [{ key: 'archived', title: "文档", isLeaf: true }] } ] }];
连接线
叶线和图标。
Lines.svelte<script lang="ts"> import { Checkbox, Tree } from '@woodger/antd'; import { treeData } from './data'; let line = $state(true); let leafIcon = $state(true); </script> <style> .example { display: grid; gap: 20px; } .settings { display: flex; flex-wrap: wrap; gap: 16px; } </style> <div class="example"> <div class="settings"> <Checkbox bind:checked={line}> {("线树")} </Checkbox> <Checkbox bind:checked={leafIcon}>{("树叶图标")}</Checkbox> </div> <Tree {treeData} showLine={line ? { showLeafIcon: leafIcon } : false} defaultExpandAll aria-label={("树与线")} /> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "项目", children: [ { key: 'docs', title: "文档", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "示例", children: [{ key: 'forms', title: "表格", isLeaf: true }] }, { key: 'archive', title: "档案", disabled: true, children: [{ key: 'archived', title: "文档", isLeaf: true }] } ] }];
您自己的图标和设计
图标/switcherIcon 片段,根 class/style。
Icons.svelte<script lang="ts"> import { Tree, type TreeEventNode } from '@woodger/antd'; import { treeData } from './data'; </script> {#snippet icon(node: TreeEventNode)}<span aria-hidden="true">{(node.isLeaf ? '▤' : node.expanded ? '▣' : '□')}</span>{/snippet} {#snippet switcher(node: TreeEventNode)}<span aria-hidden="true">{(node.expanded ? '−' : '+')}</span>{/snippet} <Tree {treeData} showIcon {icon} switcherIcon={switcher} defaultExpandAll aria-label={("自己的树图标")} class="tree-custom-root" style=" padding: 12px; border: 1px dashed var(--ant-color-border); border-radius: 8px; " />data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "项目", children: [ { key: 'docs', title: "文档", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "示例", children: [{ key: 'forms', title: "表格", isLeaf: true }] }, { key: 'archive', title: "档案", disabled: true, children: [{ key: 'archived', title: "文档", isLeaf: true }] } ] }];
文字区
全线宽
线宽和滚动
blockNode 和具有 height 的常规 scroll 容器。
Block.svelte<script lang="ts"> import { Tree } from '@woodger/antd'; import { treeData } from './data'; </script> <style> .examples { display: grid; gap: 24px; } h4 { margin: 0 0 12px; } </style> <div class="examples">{#each [false, true] as block (String(block))}<div> <h4>{(block ? "全线宽" : "文字区")}</h4> <Tree {treeData} blockNode={block} height={160} virtual={false} defaultExpandAll aria-label={(block ? "块树" : "常规树宽")} /> </div>{/each}</div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "项目", children: [ { key: 'docs', title: "文档", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "示例", children: [{ key: 'forms', title: "表格", isLeaf: true }] }, { key: 'archive', title: "档案", disabled: true, children: [{ key: 'archived', title: "文档", isLeaf: true }] } ] }];
键盘和焦点
focus 方法、tabIndex 属性和键盘事件。
Keyboard.svelte<script lang="ts"> import { Button, Tree, type TreeKey, type TreeRef } from '@woodger/antd'; import { treeData } from './data'; let tree = $state<TreeRef>(); let active = $state<TreeKey | null>(null); let lastEvent = $state('—'); </script> <style> .example { display: grid; gap: 20px; } </style> <div class="example"> <Button disabled={!tree} onclick={() => tree?.focus()}> {("将焦点放在树上")} </Button> <Tree {treeData} bind:this={tree} defaultExpandedKeys={['project']} tabIndex={-1} onActiveChange={key => { active = key; }} onFocus={() => { lastEvent = 'onFocus'; }} onBlur={() => { lastEvent = 'onBlur'; }} onKeyDown={event => { lastEvent = `onKeyDown ${event.key}`; }} aria-label={("键盘树")} /> <output aria-label={("活动树节点")}>{("积极的: ")}{(active === null ? '—' : String(active))}</output> <output aria-label={("最近的事件")}>{lastEvent}</output> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "项目", children: [ { key: 'docs', title: "文档", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "示例", children: [{ key: 'forms', title: "表格", isLeaf: true }] }, { key: 'archive', title: "档案", disabled: true, children: [{ key: 'archived', title: "文档", isLeaf: true }] } ] }];
树组件主题
反应性线条尺寸、填充和颜色;更改主题时会保留选择。
Theme.svelte<script lang="ts"> import { Checkbox, ConfigProvider, Tree } from '@woodger/antd'; import type { TreeKey } from '@woodger/antd'; import { treeData } from './data'; let enabled = $state(true); let selected = $state<TreeKey[]>(['button']); const tokens = { titleHeight: 40, switcherSize: 36, indentSize: 32, nodeSelectedBg: '#fff1b8', nodeSelectedColor: '#874d00' }; </script> <style> .settings { margin-bottom: 24px; } </style> <div class="settings"> <Checkbox bind:checked={enabled}>{("应用树令牌")}</Checkbox> </div> <ConfigProvider direction="rtl" theme={{ components: { Tree: enabled ? tokens : {} } }}> <Tree {treeData} defaultExpandAll selectedKeys={selected} aria-label={("树主题")} onSelect={keys => { selected = [...keys]; }} /> </ConfigProvider>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "项目", children: [ { key: 'docs', title: "文档", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "示例", children: [{ key: 'forms', title: "表格", isLeaf: true }] }, { key: 'archive', title: "档案", disabled: true, children: [{ key: 'archived', title: "文档", isLeaf: true }] } ] }];
线选择和标记选择是独立的。展开时会加载“Examples”分支。
文档部分
带有选择、标记、加载和重置的原始示例。
<script lang="ts">
import {
Tree,
Button,
type TreeDataNode,
type TreeKey,
type TreeCheckedKeys
} from '@woodger/antd';
const initial: TreeDataNode[] = [
{
key: 'docs',
title: "文档",
children: [
{ key: 'start', title: "入门", isLeaf: true },
{
key: 'components',
title: "组件",
children: [
{ key: 'button', title: 'Button', isLeaf: true },
{ key: 'input', title: 'Input', isLeaf: true }
]
}
]
},
{ key: 'examples', title: "示例", isLeaf: false }
];
let nodes = $state.raw(initial);
let expanded = $state<TreeKey[]>(['docs']);
let selected = $state<TreeKey[]>([]);
let checked = $state<TreeKey[] | TreeCheckedKeys>([]);
let loaded = $state<TreeKey[]>([]);
let result = $state('');
let generation = 0;
async function load(node: { key: TreeKey }) {
const version = generation;
await Promise.resolve();
if (version !== generation) {
return;
}
nodes = nodes.map(
item =>
item.key === node.key
? {
...item,
children: [
{ key: 'form-demo', title: "形式", isLeaf: true },
{ key: 'table-demo', title: "桌子", isLeaf: true }
]
}
: item
);
}
</script>
<style>
output {
display: block;
margin-top: 16px;
}
</style>
<div style="max-width:640px">
<Tree
aria-label={("剖面树")}
treeData={nodes}
checkable
showLine
blockNode
expandedKeys={expanded}
selectedKeys={selected}
checkedKeys={checked}
loadedKeys={loaded}
onLoad={keys => { loaded = keys; }}
loadData={load}
onExpand={keys => { expanded = keys; }}
onSelect={(keys, info) => {
selected = keys;
result = info.selectedNodes.map(
node => typeof node.title === 'string' ? node.title : String(node.key)
)
.join(', ');
}}
onCheck={keys => { checked = keys; }}
/>
<p>
{("线选择和标记选择是独立的。展开时会加载“Examples”分支。")}
</p>
<Button
onclick={() => {
generation++;
nodes = initial;
expanded = ['docs'];
selected = [];
checked = [];
loaded = [];
result = '';
}}
>{("重置树")}</Button>
<output aria-label={("所选部分")}>{result}</output>
</div>
节点、切换器、复选框和线使用树前缀。 DOM、ARIA ID、选定的键和未完成的加载都会被保留。 TreeSelect 有自己的树适配器。
CSS 树前缀
通用命名空间ConfigProvider和本地 prefixCls;当名称更改时,组件的状态将被保留。
<script lang="ts">
import { Checkbox, ConfigProvider, Tree, type TreeKey } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-tree' : '');
let checkedKeys = $state<readonly TreeKey[]>(['docs']);
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("树套件公共前缀")}</Checkbox>
<Checkbox bind:checked={local}>{("本地前缀树")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'tree-theme' } }}>
<div class="prefix-stage">
<Tree prefixCls={localPrefix} checkable showLine defaultExpandAll checkedKeys={checkedKeys}
onCheck={keys => checkedKeys = Array.isArray(keys) ? keys : keys.checked}
aria-label={("带前缀的树")} treeData={[
{
key: 'project', title: "项目", children: [
{ key: 'docs', title: "文档" }, { key: 'examples', title: "示例" }
]
}
]} />
<output
aria-label={("带前缀的树标记")}
>{checkedKeys.join(', ')}</output>
</div>
</ConfigProvider>
<output aria-label={("树 CSS 前缀")}>{("一般的: ")}{prefix}{(";当地的: ")}{(localPrefix
|| ("来自提供商"))}</output>
<p>
{("节点、切换器、复选框和线使用树前缀。 DOM、ARIA ID、选定的键和未完成的加载都会被保留。 TreeSelect 有自己的树适配器。")}
</p>
</div>
Ctrl、Meta 和 Shift 只执行选择,不通过标题展开。展开按钮和键盘操作相互独立。
通过标题展开
click、doubleClick 和关闭标题展开;选择与展开分别控制。
<script lang="ts">
import { Flex, Tree, type TreeExpandAction, type TreeKey } from '@woodger/antd';
let action = $state<TreeExpandAction>('click');
let expanded = $state<TreeKey[]>([]);
let selected = $state<TreeKey[]>([]);
const data = [{
key: 'src', title: 'src', children: [{
key: 'app',
title: 'App.svelte',
isLeaf: true
}]
}];
</script>
<Flex vertical gap="medium">
<label>expandAction <select value={String(action)} onchange={event => {
action = event.currentTarget.value === 'false'
? false
: event.currentTarget.value as TreeExpandAction;
expanded = [];
}}>
<option
value="false"
>false</option><option
value="click"
>click</option><option
value="doubleClick"
>doubleClick</option>
</select></label>
<Tree treeData={data} expandAction={action} expandedKeys={expanded} selectedKeys={selected}
onExpand={keys => { expanded = keys; }} onSelect={keys => { selected = keys; }}
aria-label={("通过标题展开")} />
<Flex gap="small" wrap>
<output aria-label="expandedKeys">{expanded.join(', ') || '—'}</output>
<output aria-label="selectedKeys">{selected.join(', ') || '—'}</output>
</Flex>
</Flex>
<p>
{("Ctrl、Meta 和 Shift 只执行选择,不通过标题展开。展开按钮和键盘操作相互独立。")}
</p>
普通点击选择一个文件,Ctrl/Meta 切换选择,Shift 选择可见范围。再次点击会保留选择。
文件树
DirectoryTree、Ctrl/Meta 选择和 Shift 范围选择。
<script lang="ts">
import { DirectoryTree, type TreeKey } from '@woodger/antd';
let selected = $state<TreeKey[]>([]);
const data = [{
key: 'src', title: 'src', children: [
{ key: 'app', title: 'App.svelte', isLeaf: true },
{
key: 'routes', title: 'routes', children: [{
key: 'page',
title: '+page.svelte',
isLeaf: true
}]
},
{ key: 'styles', title: 'styles.css', isLeaf: true }
]
}];
</script>
<style>
output {
display: block;
margin-block-start: 12px;
}
</style>
<DirectoryTree treeData={data} multiple defaultExpandAll selectedKeys={selected}
onSelect={keys => { selected = keys; }} aria-label={("文件树")} />
<output aria-label={("已选文件")}>{selected.join(', ') || '—'}</output>
<p>
{("普通点击选择一个文件,Ctrl/Meta 切换选择,Shift 选择可见范围。再次点击会保留选择。")}
</p>
节点自身的 switcherIcon 优先于公共图标和加载指示器。禁用节点也会触发悬停回调。
节点图标与悬停回调
节点 switcherIcon、showLeafIcon snippet 以及 disabled 节点的悬停。
<script lang="ts">
import { Tree, type TreeDataNode, type TreeEventNode } from '@woodger/antd';
let hovered = $state('—');
let data = $derived<TreeDataNode[]>([{
key: 'src', title: 'src', switcherIcon: branch,
children: [{ key: 'app', title: 'App.svelte', isLeaf: true }, {
key: 'config',
title: 'config.ts',
isLeaf: true,
disabled: true
}]
}]);
</script>
<style>
output {
display: block;
margin-block-start: 12px;
}
</style>
{#snippet branch(node: TreeEventNode)}<span
aria-hidden="true"
>{node.expanded ? '−' : '+'}</span>{/snippet}
{#snippet leaf(node: TreeEventNode)}<span
aria-hidden="true"
>{node.disabled ? '◇' : '◆'}</span>{/snippet}
<Tree treeData={data} defaultExpandAll switcherIcon={leaf} showLine={{ showLeafIcon: leaf }}
onMouseEnter={({ node }) => { hovered = String(node.key); }} onMouseLeave={() => {
hovered = '—';
}}
aria-label={("Tree 图标与悬停")} />
<output aria-label={("悬停节点")}>{hovered}</output>
<p>
{("节点自身的 switcherIcon 优先于公共图标和加载指示器。禁用节点也会触发悬停回调。")}
</p>
createTree 通过 getter 读取当前数据和 fieldNames。更新时请替换引用;未知键返回空路径。模型不会滚动 DOM。
树数据路径
无需 DOM ref 的 createTree/getPath、数据替换和 fieldNames 切换。
<script lang="ts">
import { Button, Flex, Tree, createTree, type TreeFieldNames } from '@woodger/antd';
type Entry = { id: string; caption: string; nodes?: Entry[] };
let moved = $state(false);
let data = $derived<Entry[]>([{
id: moved ? 'archive' : 'src',
caption: moved ? 'archive' : 'src',
nodes: [{ id: 'app', caption: 'App.svelte' }]
}]);
let fields = $state<TreeFieldNames>({ key: 'id', title: 'caption', children: 'nodes' });
const model = createTree(() => data, { get fieldNames() { return fields; } });
const getPath = model.getPath;
let path = $derived(getPath('app'));
</script>
<Flex vertical gap="medium">
<Tree
treeData={data}
fieldNames={fields}
expandedKeys={data.map(node => node.id)}
aria-label={("Tree 路径数据")}
/>
<Flex gap="small" wrap>
<Button onclick={() => { moved = !moved; }}>{("移动节点")}</Button>
<Button onclick={() => {
fields = fields.key === 'id' ? {
key: 'caption',
title: 'caption',
children: 'nodes'
} : { key: 'id', title: 'caption', children: 'nodes' };
}}>{("切换键字段")}</Button>
</Flex>
<output aria-label="getPath">{path.map(entity => String(entity.key)).join(' / ') || '—'}</output>
</Flex>
<p>
{("createTree 通过 getter 读取当前数据和 fieldNames。更新时请替换引用;未知键返回空路径。模型不会滚动 DOM。")}
</p>
fieldNames 映射 id/caption/nodes,无需转换数据。TreeEventNode 包含 canonical key 和状态;selectedNodes 保留原始记录及其 payload。
类型化树模式
使用 fieldNames、payload 和 canonical 事件状态的 Tree 与 DirectoryTree。
<script lang="ts">
import {
Checkbox,
DirectoryTree,
Tree,
type TreeEventNode,
type TreeFieldDataNode,
type TreeProps
} from '@woodger/antd';
type Entry = TreeFieldDataNode<{
id: number;
key: 'payload-key';
selected: 'payload-selected';
caption: { label: string };
rank: number;
}, 'nodes'>;
const leaf: Entry = {
id: 0, key: 'payload-key', selected: 'payload-selected', caption: {
label: 'App.svelte'
}, rank: 7
};
const data: Entry[] = [{
id: 1, key: 'payload-key', selected: 'payload-selected', caption: {
label: 'src'
}, rank: 3, nodes: [leaf]
}];
const fields = { key: 'id', title: 'caption', children: 'nodes' };
let directory = $state(false);
let result = $state('—');
const record: NonNullable<TreeProps<Entry>['onSelect']> = (_keys, info) => {
result = JSON.stringify({
key: info.node.key,
selected: info.selected,
nodeSelected: info.node.selected,
rank: info.node.rank,
rawKey: info.selectedNodes[0]?.key,
rawSelected: info.selectedNodes[0]?.selected,
original: info.selectedNodes[0] === leaf
});
};
</script>
{#snippet title(node: Entry)}{node.caption.label}{/snippet}
{#snippet icon(node: TreeEventNode<Entry>)}<span aria-hidden="true">{node.rank}</span>{/snippet}
<div class="settings"><Checkbox bind:checked={directory}>DirectoryTree</Checkbox></div>
{#if directory}
<DirectoryTree treeData={data} fieldNames={fields} titleRender={title} {icon} defaultExpandAll
onSelect={record} aria-label={("类型化数据树")} />
{:else}
<Tree treeData={data} fieldNames={fields} titleRender={title} {icon} showIcon defaultExpandAll
onSelect={record} aria-label={("类型化数据树")} />
{/if}
<output aria-label={("Tree 事件数据")}>{result}</output>
<p>
{("fieldNames 映射 id/caption/nodes,无需转换数据。TreeEventNode 包含 canonical key 和状态;selectedNodes 保留原始记录及其 payload。")}
</p>
<style>
.settings { margin-block-end: 12px; }
output {
display: block;
margin-block-start: 12px;
overflow-wrap: anywhere;
}
</style>
Root、item、itemIcon、itemTitle 和 itemSwitcher 接收类名和 CSS 字符串。局部值补充 provider;嵌套的 tree={} 替换整个配置。样式变化保留选择。
Semantic slots Tree
ConfigProvider.tree、局部样式 callback、嵌套配置重置和组合 title。
<script lang="ts">
import {
Button,
Checkbox,
ConfigProvider,
DirectoryTree,
Tree,
type TreeConfig,
type TreeDataNode,
type TreeKey,
type TreeProps
} from '@woodger/antd';
let local = $state(true);
let reset = $state(false);
let directory = $state(false);
let alternate = $state(false);
let selected = $state<TreeKey[]>([]);
const data: TreeDataNode[] = [{
key: 'src',
class: 'payload-node',
style: 'font-size:19px',
title: ['src', null, [false, ' / ', suffix]],
children: [{ key: 'app', title: 'App.svelte', isLeaf: true }]
}];
const provider: TreeConfig = {
class: 'tree-provider', style: 'padding:10px',
classNames: {
root: 'provider-root',
item: 'provider-item',
itemIcon: 'provider-icon',
itemTitle: 'provider-title',
itemSwitcher: 'provider-switcher'
},
styles: {
item: 'font-size:15px',
itemTitle: 'letter-spacing:1px',
itemIcon: 'color:rgb(30,90,130)'
}
};
let appearance = $derived<TreeProps['styles']>(({ props }) => ({
root: `border:1px solid ${alternate ? 'rgb(130,90,30)' : 'rgb(30,90,130)'}`,
item: 'font-size:17px',
itemTitle: `letter-spacing:${alternate ? 3 : 2}px`,
itemSwitcher: `opacity:${props.disabled ? 0.5 : 1}`
}));
const classes: TreeProps['classNames'] = ({ props }) => ({
root: props.showIcon ? 'local-icons' : 'local-root',
itemTitle: 'local-title'
});
const select: NonNullable<TreeProps['onSelect']> = keys => { selected = keys; };
</script>
{#snippet suffix(_node: TreeDataNode)}<strong>files</strong>{/snippet}
<div class="controls">
<Checkbox bind:checked={local}>{("Tree 局部样式")}</Checkbox>
<Checkbox bind:checked={reset}>{("空 provider 配置")}</Checkbox>
<Checkbox bind:checked={directory}>DirectoryTree</Checkbox>
<Button
onclick={() => { alternate = !alternate; }}
>{("更改 Tree 样式")}</Button>
</div>
<ConfigProvider tree={provider}>
<ConfigProvider tree={reset ? {} : undefined}>
{#if directory}
<DirectoryTree treeData={data} defaultExpandAll selectedKeys={selected} onSelect={select}
classNames={local ? classes : undefined} styles={local ? appearance : undefined}
aria-label={("具有 semantic slots 的树")} />
{:else}
<Tree treeData={data} showIcon defaultExpandAll selectedKeys={selected} onSelect={select}
classNames={local ? classes : undefined} styles={local ? appearance : undefined}
aria-label={("具有 semantic slots 的树")} />
{/if}
</ConfigProvider>
</ConfigProvider>
<output
aria-label={("样式树的选择")}
>{selected.join(', ') || '—'}</output>
<p>
{("Root、item、itemIcon、itemTitle 和 itemSwitcher 接收类名和 CSS 字符串。局部值补充 provider;嵌套的 tree={} 替换整个配置。样式变化保留选择。")}
</p>
<style>.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
} output {
display: block;
margin-block-start: 12px;
}</style>
模型包含 1000 个文件;虚拟视口只挂载所需行。选择键在窗口之外仍保留。Virtual=undefined 继承 provider;virtual=false 使用原生滚动渲染全部行。
Tree 与 DirectoryTree 虚拟化
1000 个文件、两个轴、RTL、行高测量、virtual 设置和 TreeRef 生命周期。
<script lang="ts">
import { Button, Checkbox, ConfigProvider, DirectoryTree, InputNumber, Tree,
type TreeKey, type TreeRef, type TreeScrollAlign, type TreeScrollOffset } from '@woodger/antd';
let directory = $state(false);
let rtl = $state(false);
let providerVirtual = $state(true);
let localOff = $state(false);
let variable = $state(false);
let measuredOffset = $state(false);
let mounted = $state(true);
let target = $state<number | null>(900);
let align = $state<TreeScrollAlign>('top');
let tree = $state<TreeRef>();
let saved = $state<TreeRef>();
let element = $state<HTMLDivElement>();
let selected = $state<TreeKey[]>([]);
let top = $state(0);
const fields = { key: 'id', title: 'caption' };
let data = $derived(Array.from({ length: 1000 }, (_, id) => ({ id,
caption: `file-${id}.ts — src/components/long-directory-name/component-${id}.svelte`,
isLeaf: true, style: `
min-width: 900px;
min-height: ${variable ? id % 3 ? 40 : 64 : 28}px;
`
})));
const rowOffset: TreeScrollOffset = ({ getSize }) => {
const size = getSize(0);
return (size.bottom ?? size.top) - size.top;
};
let Component = $derived(directory ? DirectoryTree : Tree);
</script>
<div class="controls">
<Checkbox bind:checked={directory}>DirectoryTree</Checkbox>
<Checkbox bind:checked={rtl}>RTL</Checkbox>
<Checkbox bind:checked={providerVirtual}>{("Provider 虚拟化")}</Checkbox>
<Checkbox bind:checked={localOff}>{("局部 virtual=false")}</Checkbox>
<Checkbox bind:checked={variable}>{("不同行高")}</Checkbox>
<Checkbox
bind:checked={measuredOffset}
>{("偏移首行高度")}</Checkbox>
<Checkbox bind:checked={mounted}>{("显示虚拟树")}</Checkbox>
</div>
<div class="controls">
<InputNumber
aria-label={("行键或索引")}
bind:value={target}
min={0}
max={999}
precision={0}
style="width:100px"
/>
<label>align <select
bind:value={align}
><option
value="top"
>top</option><option
value="bottom"
>bottom</option><option
value="auto"
>auto</option></select></label>
<Button disabled={!tree} onclick={() => tree?.scrollTo({
key: target ?? 0,
align,
offset: measuredOffset ? rowOffset : 0
})}>scrollTo(key)</Button>
<Button
disabled={!tree}
onclick={() => tree?.scrollTo({ index: target ?? 0, align })}
>scrollTo(index)</Button>
<Button disabled={!tree || !providerVirtual || localOff} onclick={() => tree?.scrollTo({
top: 120,
left: 160
})}>scrollTo(top, left)</Button>
<Button disabled={!tree} onclick={() => tree?.scrollTo({ top: 0, left: 0 })}>
{("回到树起点")}
</Button>
<Button disabled={!tree} onclick={() => tree?.focus()}>focus()</Button>
<Button disabled={!tree} onclick={() => tree?.blur()}>blur()</Button>
<Button disabled={!tree} onclick={() => tree?.scrollTo(null)}>scrollTo(null)</Button>
<Button
disabled={!tree}
onclick={() => { saved = tree; }}
>{("保存 TreeRef")}</Button>
<Button
disabled={!saved}
onclick={() => { saved?.scrollTo(0); saved?.focus(); saved?.blur(); }}
>{("调用已保存的 TreeRef")}</Button>
</div>
<ConfigProvider virtual={providerVirtual} direction={rtl ? 'rtl' : 'ltr'}>
<div class="viewport">
{#if mounted}
<Component treeData={data} fieldNames={fields} height={210} itemHeight={32} scrollWidth={1200}
virtual={localOff ? false : undefined} itemScrollOffset={8}
selectedKeys={selected} onSelect={keys => { selected = keys; }}
onScroll={event => { top = event.currentTarget.scrollTop; }}
bind:this={tree} bind:nativeElement={element} aria-label={("虚拟文件树")} />
{/if}
</div>
</ConfigProvider>
<output
aria-label={("虚拟树选择")}
>{selected.join(', ') || '—'}</output>
<output aria-label="TreeRef nativeElement">{element?.tagName ?? '—'}</output>
<output aria-label="Tree onScroll">{Math.round(top)}</output>
<p>
{("模型包含 1000 个文件;虚拟视口只挂载所需行。选择键在窗口之外仍保留。Virtual=undefined 继承 provider;virtual=false 使用原生滚动渲染全部行。")}
</p>
<style>
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.viewport { min-width:0; }
output {
display: block;
margin-block-start: 8px;
overflow-wrap: anywhere;
}
</style>
createTree 查找祖先,调用方更新 expandedKeys,随后在 tick 后调用 TreeRef.scrollTo。AutoExpand 只在非受控模式下添加目标键,不会自动展开所有祖先。
滚动到嵌套节点
createTree/getPath 查找祖先;调用方在 TreeRef.scrollTo 前展开路径。
<script lang="ts">
import { tick } from 'svelte';
import {
Button,
Input,
Tree,
createTree,
type TreeDataNode,
type TreeKey,
type TreeRef
} from '@woodger/antd';
const data: TreeDataNode[] = [{
key: 'project', title: 'project', children:
Array.from({ length: 20 }, (_, folder) => ({
key: `folder-${folder}`,
title: `folder-${folder}`,
children:
Array.from({ length: 50 }, (_, file) => ({
key: `file-${folder}-${file}`,
title: `file-${folder}-${file}.svelte`,
isLeaf: true
}))
}))
}];
const model = createTree(data);
let target = $state('file-19-49');
let expanded = $state<TreeKey[]>([]);
let tree = $state<TreeRef>();
async function reveal() {
const path = model.getPath(target);
if (!path.length) {
return;
}
expanded = [...new Set([...expanded, ...path.slice(0, -1).map(entity => entity.key)])];
await tick();
tree?.scrollTo({ key: target, align: 'top' });
}
async function reset() {
expanded = [];
await tick();
tree?.scrollTo(0);
}
</script>
<div class="controls">
<Input
aria-label={("嵌套节点键")}
bind:value={target}
style="width:180px"
/>
<Button disabled={!tree} onclick={reveal}>{("展开路径并滚动")}</Button>
<Button disabled={!tree} onclick={reset}>{("收起树")}</Button>
</div>
<Tree treeData={data} height={210} expandedKeys={expanded} onExpand={keys => { expanded = keys; }}
bind:this={tree} aria-label={("滚动到嵌套节点")} />
<output aria-label={("滚动路径")}>{model.getPath(target).map(entity => String(
entity.key
)).join(' / ') || '—'}</output>
<p>
{("createTree 查找祖先,调用方更新 expandedKeys,随后在 tick 后调用 TreeRef.scrollTo。AutoExpand 只在非受控模式下添加目标键,不会自动展开所有祖先。")}
</p>
<style>.controls {
display:flex;
flex-wrap:wrap;
gap:8px;
margin-bottom:12px;
} output {
display:block;
margin-block-start:12px;
overflow-wrap:anywhere;
}</style>
API
ant.design 6.7.0 的十三个主题已映射至公开 Svelte API。支持 DirectoryTree、虚拟化、scrollTo、createTree/getPath、拖放和 collapse motion。
| 主题 | 示例或限制 |
|---|---|
| Basic | checkable、disabled 和初始键。 |
| Controlled Tree | 揭示和多项选择。 |
| draggable | 在 onDrop 中移动数据,支持 allowDrop、RTL 和虚拟窗口。 |
| load data asynchronously | 错误、重试、loadedKeys 和清理。 |
| Searchable | 在示例模型中突出显示并揭示父母。 |
| Tree with line | showLine 和 showLeafIcon:boolean 或 snippet。 |
| Customize Icon | TreeEventNode 的片段。 |
| directory | DirectoryTree 以及通过 expandAction 展开标题。 |
| Customize collapse/expand icon | switcherIcon 是从 TreeEventNode 扩展而来的。 |
| Virtual scroll | 虚拟视口、两个轴和 RTL;virtual=false 启用原生模式。 |
| Scroll to nested node | TreeRef.scrollTo 以及通过 createTree/getPath 展开祖先。 |
| Block Node | 全线宽。 |
| Custom semantic dom styling | 五个 semantic slots、callback 和 ConfigProvider.tree。 |
Tree
| 属性 | 描述 | 类型 | 默认 |
|---|---|---|---|
draggable | boolean、原始节点判断函数或 {nodeDraggable,icon};icon=false 隐藏手柄。 | TreeDraggable<Data> | false |
allowDrop | 检查原始 dragNode/dropNode 数据和相对位置 -1/0/1,drop 前会再次检查。 | TreeAllowDrop<Data> | — |
onDragStart | 开始 HTML5 拖动,提供原生事件和节点状态。 | (info: TreeDragInfo<Data>) => void | — |
onDragEnter | 进入目标;expandedKeys 为延迟展开前的键,onExpand 接收新键。 | (info: TreeDragEnterInfo<Data>) => void | — |
onDragOver | 更新放置位置。 | (info: TreeDragInfo<Data>) => void | — |
onDragLeave | 离开放置目标。 | (info: TreeDragInfo<Data>) => void | — |
onDragEnd | 结束拖动并释放资源。 | (info: TreeDragInfo<Data>) => void | — |
onDrop | 使用方移动 treeData。dropPosition 为同级索引加 -1/0/1;dropToGap 区分移入节点内部。 | (info: TreeDropInfo<Data>) => void | — |
motion | 自定义 CSS 阶段、异步 prepare 和截止时间;false 禁用过渡,null/undefined 启用默认动画。 | TreeMotionConfig | false | null | collapse |
prefixCls | 组件及其部件的完整 CSS 前缀。非空本地 prop 优先;空字符串和 undefined 继承ConfigProvider。主题的命名空间是单独设置的。 | string | ConfigProvider.prefixCls + "-tree" |
treeData | 具有稳定唯一键的类型化原始数据。 | readonly Data[] | [] |
fieldNames | 键、标题和子数据的字段名;Tree 和 DirectoryTree 均支持。 | TreeFieldNames | key/title/children |
classNames | root/item/itemIcon/itemTitle/itemSwitcher 的类名:record 或接收 props 的 callback。 | TreeSemanticValue<TreeClassNames, Data> | — |
styles | 五个 semantic slots 的 CSS 字符串:record 或接收 props 的 callback。 | TreeSemanticValue<TreeStyles, Data> | — |
expandedKeys | 受控部署;在 onExpand 中更新。 | readonly TreeKey[] | 内部状态 |
defaultExpandedKeys | 初次开业。 | readonly TreeKey[] | [] |
defaultExpandAll | 初始化时扩展源数据。 | boolean | false |
autoExpandParent | 显示父母控制的钥匙。 | boolean | false |
defaultExpandParent | 在初始化时展开父级。 | boolean | true |
expandAction | 标题展开;带修饰键的 click 只改变选择。 | false | "click" | "doubleClick" | false |
selectedKeys | 受控的行选择。 | readonly TreeKey[] | 内部状态 |
defaultSelectedKeys | 初始行选择。 | readonly TreeKey[] | [] |
multiple | 多项选择树。 | boolean | false |
selectable | 允许行选择。 | boolean | true |
checkable | 显示复选框。 | boolean | false |
checkStrictly | 父母和孩子的独立标记。 | boolean | false |
checkedKeys | 受控标记;在严格 mode 下,对象被 checked/halfChecked。 | readonly TreeKey[] | TreeCheckedKeys | 内部状态 |
defaultCheckedKeys | 初始标记。 | readonly TreeKey[] | [] |
loadData | 加载儿童。所有者更新 treeData。 | (node: TreeEventNode) => PromiseLike<unknown> | — |
loadedKeys | 受控的加载分支集;在 onLoad 中更新。 | readonly TreeKey[] | 内部状态 |
onExpand | 要求披露。 | (keys, {expanded, node, nativeEvent}) => void | — |
onSelect | 选择和 selectedNodes。 | (keys, info) => void | — |
onCheck | 检查、halfCheckedKeys 和 checkedNodes。 | (keys, TreeCheckInfo) => void | — |
onLoad | 下载成功完成。 | (keys, {event, node}) => void | — |
filterTreeNode | 匹配突出显示;不删除行。 | (node: TreeEventNode) => boolean | — |
titleRender | 您的节点文本。 | Snippet<[Data]> | fieldNames 指定的 title 字段 |
showLine | 连接线。 | boolean | {showLeafIcon: boolean | Snippet<[TreeEventNode]>} | false |
showIcon | 显示节点 icon 或通用 icon。 | boolean | false |
icon | 通用图标。 | Snippet<[TreeEventNode]> | — |
switcherIcon | 公共展开图标;加载状态优先。 | Snippet<[TreeEventNode]> | 标准 |
switcherLoadingIcon | 正在加载图标。 | Snippet<[TreeEventNode]> | loading |
blockNode | 按容器划分的线宽。 | boolean | false |
height | 视口高度;undefined/0 无高度限制地渲染所有展开行。 | number | — |
virtual | 设置高度时启用虚拟窗口;false 保留 DOM 中的全部行。 | boolean | ConfigProvider.virtual ?? true |
itemHeight | 测量前的估计高度;零关闭虚拟窗口。 | number | Tree tokens |
scrollWidth | 用于水平滚动的虚拟内容宽度。 | number | — |
itemScrollOffset | 活动节点自动滚动的偏移。 | number | 0 |
onScroll | Holder 的滚动事件;也支持原生 onscroll。 | (event: UIEvent) => void | — |
tabIndex | 树在键盘焦点顺序中的位置。tabindex 属性优先。 | number | 0 |
onFocus | 树确定活动节点后获得焦点。 | (event: FocusEvent) => void | — |
onBlur | 树失去焦点。 | (event: FocusEvent) => void | — |
onKeyDown | 树处理按键后触发的事件。 | (event: KeyboardEvent) => void | — |
onMouseDown | 焦点移动前按下鼠标按钮。 | (event: MouseEvent) => void | — |
onContextMenu | 节点的 onRightClick 之后触发的树上下文菜单事件。 | (event: MouseEvent) => void | — |
activeKey | 受控的活动键盘节点。 | TreeKey | null | 内部状态 |
onMouseEnter | 悬停行内容,包括 disabled 节点。 | ({event, node}) => void | — |
onMouseLeave | 离开行内容时提供当前 TreeEventNode。 | ({event, node}) => void | — |
onActiveChange | 更改活动节点。 | (key: TreeKey | null) => void | — |
TreeDataNode
| 属性 | 描述 | 类型 | 默认 |
|---|---|---|---|
key | 唯一的稳定标识符。 | string | number | bigint | 必需的 |
title | 可用节点名称。 | TreeTitleContent<TreeDataNode> | --- |
children | 子节点。 | readonly TreeDataNode[] | — |
isLeaf | 叶属性; false 允许加载分支。 | boolean | 通过孩子/loadData |
disabled | 节点关闭并标记传播边界。 | boolean | false |
disableCheckbox | 仅禁用复选框。 | boolean | false |
checkable | 显示该节点的复选框。 | boolean | 一般可检查 |
selectable | 允许选择该节点。 | boolean | 一般可选 |
switcherIcon | 节点图标优先于公共 renderer 和加载指示器。 | Snippet<[TreeEventNode]> | 公共 switcherIcon |
icon | 节点图标。 | Snippet<[TreeEventNode]> | 通用图标 |
class | 节点字符串类。 | string | — |
style | CSS 节点字符串。 | string | — |
TreeTitleContent 支持字符串、数字、嵌套数组和接收原始节点的 snippet;boolean/null/undefined 不输出内容。Icon 和 titleRender 保留 Data 类型。bind:nativeElement 返回外部 root;bind:this 提供带有 focus/blur/scrollTo 的 TreeRef。height 定义虚拟视口;virtual=false 保留原生滚动。
DirectoryTree 继承 TreeProps;默认值为 expandAction="click"、showIcon=true 和 blockNode=true。多选使用 Ctrl/Meta 和 Shift。
createTree(dataOrGetter, config).getPath(key) 返回 TreeDataEntity[]:node、nodes、key、pos、index、level、parent 和 children。模型、Tree 和 DirectoryTree 支持相同的 fieldNames 映射;无需转换 payload。
TreeRef 方法
Tree 和 DirectoryTree 的 TreeRef 提供 focus(options?)、blur() 和 scrollTo(config?)。nativeElement 仍是单独的可绑定属性,卸载时清除。
TreeScrollConfig 接收数字、{top,left}、key 或 index,并支持 align=top/bottom/auto 和 offset。offset 是数字或带有 getSize(startKey,endKey?) 的纯 TreeScrollOffset 函数。未知 key 保持位置不变;null/undefined 显示滚动条。
RTL 中的 left 也是非负逻辑位置。Key 请求中的 autoExpand 只向非受控 expandedKeys 添加目标键,不展开祖先,也不调用 onExpand。卸载后,已保存的 ref 安全地停止执行操作。
Semantic DOM
通过 classNames/styles 和 ConfigProvider.tree 提供五个 semantic slots。值为 record 或接收 props 的 callback;CSS 使用字符串。role=tree 使用 aria-activedescendant;treeitem 报告层级、选择、勾选和展开状态。
| 元素 | 目的 |
|---|---|
root | 树的外部根节点;普通 style 保持优先级。 |
item | 节点行;semantic 样式补充数据中的 class/style。 |
itemIcon | 节点图标区域。 |
itemTitle | 标题区域,包括 snippet 和嵌套内容。 |
itemSwitcher | 展开按钮或叶子区域。 |
| 元素 | 目的 |
|---|---|
.ant-tree | 外部根、class/style 和 nativeElement。 |
.ant-tree-list | 可聚焦的带有 aria-activedescendant 的 role=tree。 |
.ant-tree-list-holder | 虚拟或原生滚动视口。 |
.ant-tree-treenode | 带有状态和级别的 role=treeitem。 |
.ant-tree-switcher | 展开按钮从 Tab 键顺序中排除。 |
.ant-tree-checkbox | 按钮 role=checkbox。 |
.ant-tree-node-content-wrapper | 线路选择按钮。 |
.ant-tree-iconEle | 图标区域。 |
.ant-tree-list-holder-inner | 已挂载的虚拟行;位置随滚动更新。 |
.ant-tree-list-scrollbar-vertical | 虚拟视口的垂直滚动条;RTL 中位于左侧。 |
.ant-tree-list-scrollbar-horizontal | scrollWidth 大于视口宽度时的水平滚动条。 |
.ant-tree-title | 用作可用名称的名称。 |
注册令牌
Tree 令牌控制行高、展开按钮大小、缩进和状态颜色。示例切换主题时保留选择和 RTL。Directory 令牌设置 DirectoryTree 已选行的颜色。
| 代币 | 目的 |
|---|---|
titleHeight | 线高。 |
switcherSize | 开口宽度。 |
indentSize | 水平嵌套步骤。 |
nodeHoverBg | 悬停背景。 |
nodeHoverColor | 悬停文本。 |
nodeSelectedBg | 所选节点的背景。 |
nodeSelectedColor | 所选节点的文本。 |
directoryNodeSelectedBg | DirectoryTree 已选行的背景。 |
directoryNodeSelectedColor | DirectoryTree 已选行的文本。 |
| 代币 | 意义 |
|---|---|
colorBgContainer | #ffffff |
colorText | rgba(0,0,0,0.88) |
colorTextDisabled | rgba(0,0,0,0.25) |
colorPrimary | #2f54eb |
controlInteractiveSize | 16 |
fontSize | 14 |
paddingXS | 8 |
FAQ
行选择和标记是一种状态?
selectedKeys 控制选择,checkedKeys 控制复选标记,expandedKeys 控制扩展。分别通过 onSelect、onCheck 和 onExpand 接受它们。
checkStrictly 是如何工作的?
如果 false,则父母和孩子有联系并可以获得部分分数。如果为 true,则检查是独立的,并且 onCheck 返回 checked/halfChecked。
为什么 defaultExpandAll 没有展开加载的节点?
初始道具已被阅读。对于以后的数据,更新 expandedKeys 或在加载后创建树。
filterTreeNode 是否隐藏不匹配的行?
不,它突出显示节点。家长披露、单独的数据过滤和文本突出显示由应用程序组织。
有虚拟化和 scrollTo 吗?
支持。正数 height 和启用的 virtual 定义虚拟视口。TreeRef.scrollTo 接收坐标、键或索引;祖先展开由调用方管理。
如何启用拖放和动画?
draggable 启用拖动,但 treeData 由使用方在 onDrop 中更新。默认动画已启用;motion=false 可以禁用。上方示例演示这两种模式。
如何通过键盘进行控制?
使用箭头、Home/End、Enter 和空格键。焦点仍然在树上; activeKey 与选择和复选标记分开报告活动节点。