Tree
Trees: expansion, selection, marks, search, asynchronous loading and keyboard.
When to use
Tree displays folders, documentation sections, or organizational hierarchy. Branches can be expanded, rows can be selected, and nodes can be marked with a checkbox. For a tree inside a compact input field, use TreeSelect.
Pass nested treeData with unique persistent key. The key identifies a node in the entire tree, not just among its neighbors; title is responsible for the signature.
CSS Tree Prefixes show global ConfigProvider.prefixCls and local prefixCls without resetting state. Nodes, switcher, checkbox and lines use the tree prefix. DOM, ARIA IDs, selected keys and unfinished loading are preserved. TreeSelect has its own tree adapter.
Expanding, selecting and markings
expandedKeys, selectedKeys and checkedKeys are three independent states. Changing one should not replace the other two. For a managed tree, accept new keys via the appropriate callback.
| Problem | Setting | Example |
|---|---|---|
| Show nested nodes | treeData, defaultExpandedKeys |
Ordinary tree |
| Manage states externally | expandedKeys, selectedKeys, checkedKeys |
Managed tree |
| Select multiple lines | multiple, onSelect |
Ordinary tree |
| Compare checkbox rules | checkable, checkStrictly |
Related and independent marks |
| Load child nodes | loadData, loadedKeys |
Loading with error and retry |
defaultExpandedKeys, defaultSelectedKeys and defaultCheckedKeys are read when the tree is created. defaultExpandAll also applies to the initial data set. For data that arrives later, manage expandedKeys or create a Tree after receiving it.
checkable enables checkbox. By default, marks are propagated between parents and children, and an incomplete branch receives a partial mark. checkStrictly disables the connection: onCheck returns a checked/halfChecked object. A disabled node stops the propagation of marks through itself. selectable and disableCheckbox separately control row selection and checkbox availability.
Loading and searching
loadData receives a TreeEventNode and returns a Promise. For an unloaded branch, set isLeaf=false; after the response, add children to treeData and complete the Promise. loadedKeys stores the keys of completed downloads, onLoad reports their update. In a managed scenario, accept the new loadedKeys so that the loading state matches the data.
Asynchronous example shows error and reopening. The error message and request belong to the application; When leaving the page, free up your timers and resources.
filterTreeNode highlights matching nodes rather than removing other rows. Search separately calculates the parents of the expandedKeys matches and draws the mark via titleRender. With your own filter, save the necessary ancestors and stable keys.
Design and keyboard
showLine draws connections, showIcon includes icons. titleRender, icon, switcherIcon and switcherLoadingIcon accept Svelte snippets; TreeEventNode contains node states, including expanded, selected, and loading. Example icons changes the view without changing the keys.
blockNode stretches the row; height defines a virtual viewport. With virtual=false, all expanded rows remain in the DOM with native scrolling. API coverage lists the available settings.
Dragging nodes demonstrates draggable, allowDrop and onDrop for Tree/DirectoryTree, including RTL and virtual scrolling. The application moves the data. dropToGap=false means a drop inside the node; for a gap, subtract the last index in node.pos from info.dropPosition to obtain -1 or 1. dragNodesKeys contains the source key and all descendants. nodeDraggable=false disables both dragging and dropping for that row; icon=false only hides the handle. disabled prevents starting a drag, but restrict targets separately with allowDrop. onDragEnter reports keys before delayed expansion; onExpand receives the new keys after 800 ms.
Tree expansion motion compares default collapse, custom CSS phases and motion=false. null/undefined enable the default transition; start/active callbacks return CSS strings, and prepare may return a Promise. motionDeadline finishes a transition when no CSS event arrives. The library respects reduced motion; theme.token.motion=false skips CSS phases while preserving prepare. Multiple simultaneous expandedKeys changes apply without a transition. Virtual motion groups are limited to the window; finishing a drag, replacing data and unmounting cancel stale callbacks.
The root class/style and class/style of individual nodes are available. Tree component design tokens operate and are updated reactively; DirectoryTree tokens style selected rows in the file tree. Example theme retains the selection when changing the design.
The focus remains on role=tree, the active node is passed through aria-activedescendant. Arrows move it and open/collapse branches, Home/End move to the edges. Enter expands a branch or selects a leaf, Space changes the mark or selection. Keyboard example shows activeKey and focus operation. bind:nativeElement returns the outer root after mount.
In Tree and DirectoryTree, tabIndex sets the focus order. In the example, tabIndex={-1} skips the tree during Tab navigation, and the button focuses it with focus(). onFocus and onBlur report focus changes. onKeyDown receives the native event after the tree handles the keystroke. onMouseDown and onContextMenu receive mouse events on the tree.
Expansion, files and data paths
Title expansion supports expandAction=false, click and doubleClick. Ctrl/Meta/Shift only change selection; the switcher and keyboard work independently.
The file tree uses DirectoryTree. Defaults are showIcon=true, blockNode=true and expandAction="click". With multiple, a normal click selects one row, Ctrl/Meta toggles keys, and Shift selects a range of visible rows. Clicking again does not clear selection.
Node icons demonstrate TreeDataNode.switcherIcon and a showLine.showLeafIcon snippet. A node icon overrides the shared switcher and loading indicator; onMouseEnter/onMouseLeave receive the event and current TreeEventNode, including disabled nodes.
Data paths use createTree(dataOrGetter, config).getPath(key), rather than a DOM ref. getPath returns TreeDataEntity[] from the root to the node; each entity contains node, nodes, key, index, pos, level, parent and children. An unknown key returns an empty array. For reactive updates, pass a data getter and a config.fieldNames getter; replace the array and fieldNames references. The same fieldNames mapping is supported by the model, Tree and DirectoryTree; the original payload needs no conversion. The model works during SSR, creates no DOM and provides no scrollTo.
Data schemas and semantic slots
The typed schema passes original records through treeData and fieldNames for key/title/children. An empty fieldNames entry uses the standard field name. TreeProps<Data>, TreeEventNode<Data> and TreeCheckInfo<Data> preserve payload types; TreeFieldDataNode<Payload, ChildFieldName> describes recursive data. State and the canonical key in event nodes override colliding payload fields, while selectedNodes/checkedNodes contain original records. Node.selected reflects the state before selection; info.selected reports the action result.
TreeTitleContent<Data> supports text, numbers, nested arrays and snippets receiving the original record. boolean, null and undefined render nothing; an absent title uses "---". A snippet in the title field takes precedence over titleRender. Use titleRender for an object-valued title: objects are not converted to text automatically.
Semantic slots provide classNames/styles for root, item, itemIcon, itemTitle and itemSwitcher. A record or callback receiving props returns classes or CSS strings; callbacks must compute appearance without changing state. ConfigProvider.tree applies to Tree and DirectoryTree, but not the internal TreeSelect tree. Local classes accumulate with provider classes; CSS order is provider styles, provider style for root, local styles, then the ordinary style for root. Node class/style remain available; semantic item style follow node.style.
A nested ConfigProvider with tree=undefined inherits configuration; tree={} replaces the complete record. Appearance changes preserve selection, DOM and pending loading. The ordinary style remains on the outer root rather than the inner list.
Virtualization and scrolling
The virtual tree shows 1000 files in Tree and DirectoryTree with fieldNames. Only a window of rows is mounted, while selectedKeys belongs to the complete model. Without height, or with height=0, all expanded rows render without a height constraint. virtual=undefined inherits ConfigProvider.virtual; without a provider value, Tree enables virtualization. virtual=false retains every row and native scrolling.
itemHeight overrides the initial estimate from Tree tokens; itemHeight=0 disables the window. After mount, actual rows are measured including margins, and measurements are retained by key until unmount. SSR uses the initial estimate without DOM measurements, loading or timers. loadData for initially expanded branches starts when they enter the mounted window.
scrollWidth defines virtual content width. Wheel, Shift+wheel, touch and scrollbar dragging support both axes, including RTL. The example demonstrates two-dimensional coordinates in virtual mode. TreeRef.scrollTo accepts a number or {top,left}, or {key,align,offset} or {index,align,offset}. align supports top/bottom/auto. left is a nonnegative logical position in RTL as well. offset is a number or a pure TreeScrollOffset function; getSize(startKey,endKey?) returns measured/estimated top/bottom. An unknown endKey yields bottom=undefined; NaN/Infinity values for offset become zero.
scrollTo does not select a node. An unknown key leaves the position unchanged; null/undefined show the scrollbar. A later request supersedes the previous one. itemScrollOffset applies to automatic scrolling of the active node; onScroll receives a holder event, while bind:nativeElement still points to the outer root. Refs clear on unmount, and a saved TreeRef safely stops performing actions.
Scrolling to a nested node uses createTree.getPath to find ancestors. The owner updates expandedKeys, awaits tick and calls scrollTo. autoExpand on a key request adds only the target key in uncontrolled mode, without expanding ancestors or calling onExpand. Update expandedKeys explicitly for a controlled tree.
Examples
Drag a file onto another row or between rows. The onDrop handler updates treeData; locked is not a valid target, and LICENSE cannot be dragged.
Dragging nodes
Tree and DirectoryTree: moving data, allowDrop, custom handles, RTL and a virtual window.
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}>{("Drag-and-drop virtual window")}</Checkbox> <Checkbox bind:checked={inside}>{("Allow dropping inside a node")}</Checkbox> <Checkbox bind:checked={handle}>{("Show drag handle")}</Checkbox> <Button onclick={() => { data = initial(); expanded = ['components', 'guides', 'locked']; lastDrop = '—'; }}>{("Reset tree order")}</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={("Draggable tree")} /> </ConfigProvider> <output aria-label={("Last tree drop")}>{lastDrop}</output> <p> {("Drag a file onto another row or between rows. The onDrop handler updates treeData; locked is not a valid target, and LICENSE cannot be dragged.")} </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)); }
Default collapse motion is enabled. A custom object defines CSS phases and callbacks; motion=false disables transitions. The library respects reduced motion.
Tree expansion motion
Default collapse, custom phases, disabling motion and preserving neighboring input.
<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 branch motion")}</Checkbox>
<Checkbox bind:checked={custom}>{("Custom motion phases")}</Checkbox>
<Button onclick={() => { expanded = expanded.includes('src') ? [] : ['src']; }}>
{("Expand or collapse branch")}
</Button>
</div>
<Component treeData={data} expandedKeys={expanded} onExpand={keys => { expanded = keys; }}
motion={enabled ? custom ? customMotion : undefined : false} aria-label={("Tree with motion")} />
<div
class="draft"
><Input
bind:value={draft}
aria-label={("Draft beside the tree")}
/></div>
<output aria-label={("Completed Tree phases")}>{completed}</output>
<p>
{("Default collapse motion is enabled. A custom object defines CSS phases and callbacks; motion=false disables transitions. The library respects reduced motion.")}
</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>
Ordinary tree
Initial keys, disabled and 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={("Ordinary tree")} />data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Project", children: [ { key: 'docs', title: "Documentation", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Examples", children: [{ key: 'forms', title: "Forms", isLeaf: true }] }, { key: 'archive', title: "Archive", disabled: true, children: [{ key: 'archived', title: "Document", isLeaf: true }] } ] }];
Managed tree
Independent expandedKeys and 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={("Managed tree")} /> <Button onclick={() => { expanded = ['project']; selected = []; }}> {("Reset managed tree")} </Button> <output aria-label={("Selecting a managed tree")} >{("Selected: ")}{(selected.map(String).join(', ') || '—')}</output> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Project", children: [ { key: 'docs', title: "Documentation", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Examples", children: [{ key: 'forms', title: "Forms", isLeaf: true }] }, { key: 'archive', title: "Archive", disabled: true, children: [{ key: 'archived', title: "Document", isLeaf: true }] } ] }];
Related and independent marks
Conduction, partial state and 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 = []; }}> {("Independent marks Tree")} </Checkbox> <Tree {treeData} checkable checkStrictly={strict} checkedKeys={checked} onCheck={next => { checked = next; }} defaultExpandAll aria-label={("Tree of marks")} /> <output aria-label={("Marked Tree keys")}>{("Noted: ")}{(keys .map(String).join(', ') || '—')}</output> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Project", children: [ { key: 'docs', title: "Documentation", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Examples", children: [{ key: 'forms', title: "Forms", isLeaf: true }] }, { key: 'archive', title: "Archive", disabled: true, children: [{ key: 'archived', title: "Document", isLeaf: true }] } ] }];
Loading with error and repeating
Promise loadData, loadedKeys and clear on reset.
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++; }}> {("Reset tree loading")} </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: "Deleted partitions", 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 = ("Failed to load partitions. Uncheck the error and expand the branch again."); reject(new Error((error))); } else { nodes = nodes.map( item => item.key === node.key ? { ...item, children: [ { key: 'remote-form', title: "Forms on the server", isLeaf: true }, { key: 'remote-table', title: "Tables on the server", 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}> {("Tree loading error")} </Checkbox> <Tree treeData={nodes} {loadData} loadedKeys={loaded} onLoad={keys => { if (active) loaded = keys; }} aria-label={("Loading Tree sections")} /> {#if error}<Alert type="error" title={("Tree loading error")} description={error} showIcon />{/if} <output aria-label={("Loaded Tree keys")} >{("Uploaded: ")}{(loaded.map(String).join(', ') || '—')}</output> </div>
Search and highlight
Search reveals parents; filterTreeNode highlights matches.
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={("Search for Tree section")} 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={("Search in tree")} /></div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Project", children: [ { key: 'docs', title: "Documentation", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Examples", children: [{ key: 'forms', title: "Forms", isLeaf: true }] }, { key: 'archive', title: "Archive", disabled: true, children: [{ key: 'archived', title: "Document", isLeaf: true }] } ] }];
Connecting lines
Lines and leaf icons.
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}> {("Tree Lines")} </Checkbox> <Checkbox bind:checked={leafIcon}>{("Tree Leaf Icons")}</Checkbox> </div> <Tree {treeData} showLine={line ? { showLeafIcon: leafIcon } : false} defaultExpandAll aria-label={("Tree with lines")} /> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Project", children: [ { key: 'docs', title: "Documentation", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Examples", children: [{ key: 'forms', title: "Forms", isLeaf: true }] }, { key: 'archive', title: "Archive", disabled: true, children: [{ key: 'archived', title: "Document", isLeaf: true }] } ] }];
Own icons and design
Icon/switcherIcon snippets, root 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={("Own Tree icons")} 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: "Project", children: [ { key: 'docs', title: "Documentation", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Examples", children: [{ key: 'forms', title: "Forms", isLeaf: true }] }, { key: 'archive', title: "Archive", disabled: true, children: [{ key: 'archived', title: "Document", isLeaf: true }] } ] }];
Text area
Full line width
Line width and scrolling
blockNode and a regular scroll container with height.
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 ? "Full line width" : "Text area")}</h4> <Tree {treeData} blockNode={block} height={160} virtual={false} defaultExpandAll aria-label={(block ? "Block tree" : "Regular tree width")} /> </div>{/each}</div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Project", children: [ { key: 'docs', title: "Documentation", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Examples", children: [{ key: 'forms', title: "Forms", isLeaf: true }] }, { key: 'archive', title: "Archive", disabled: true, children: [{ key: 'archived', title: "Document", isLeaf: true }] } ] }];
Keyboard and Focus
The focus method, the tabIndex property, and keyboard events.
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()}> {("Give focus to tree")} </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={("Keyboard Tree")} /> <output aria-label={("Active Tree node")}>{("Active: ")}{(active === null ? '—' : String(active))}</output> <output aria-label={("Latest event")}>{lastEvent}</output> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Project", children: [ { key: 'docs', title: "Documentation", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Examples", children: [{ key: 'forms', title: "Forms", isLeaf: true }] }, { key: 'archive', title: "Archive", disabled: true, children: [{ key: 'archived', title: "Document", isLeaf: true }] } ] }];
Tree Component Theme
Reactive line sizes, paddings and colors; the selection is retained when changing the theme.
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}>{("Apply Tree tokens")}</Checkbox> </div> <ConfigProvider direction="rtl" theme={{ components: { Tree: enabled ? tokens : {} } }}> <Tree {treeData} defaultExpandAll selectedKeys={selected} aria-label={("Tree Theme")} onSelect={keys => { selected = [...keys]; }} /> </ConfigProvider>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Project", children: [ { key: 'docs', title: "Documentation", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Examples", children: [{ key: 'forms', title: "Forms", isLeaf: true }] }, { key: 'archive', title: "Archive", disabled: true, children: [{ key: 'archived', title: "Document", isLeaf: true }] } ] }];
Line selection and mark selection are independent. The "Examples" branch is loaded when expanded.
Documentation sections
Original example with selection, marks, loading and resetting.
<script lang="ts">
import {
Tree,
Button,
type TreeDataNode,
type TreeKey,
type TreeCheckedKeys
} from '@woodger/antd';
const initial: TreeDataNode[] = [
{
key: 'docs',
title: "Documentation",
children: [
{ key: 'start', title: "Getting started", isLeaf: true },
{
key: 'components',
title: "Components",
children: [
{ key: 'button', title: 'Button', isLeaf: true },
{ key: 'input', title: 'Input', isLeaf: true }
]
}
]
},
{ key: 'examples', title: "Examples", 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: "Shape", isLeaf: true },
{ key: 'table-demo', title: "Table", isLeaf: true }
]
}
: item
);
}
</script>
<style>
output {
display: block;
margin-top: 16px;
}
</style>
<div style="max-width:640px">
<Tree
aria-label={("Partition tree")}
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>
{("Line selection and mark selection are independent. The \"Examples\" branch is loaded when expanded.")}
</p>
<Button
onclick={() => {
generation++;
nodes = initial;
expanded = ['docs'];
selected = [];
checked = [];
loaded = [];
result = '';
}}
>{("Reset tree")}</Button>
<output aria-label={("Selected section")}>{result}</output>
</div>
Nodes, switcher, checkbox and lines use the tree prefix. DOM, ARIA IDs, selected keys and unfinished loading are preserved. TreeSelect has its own tree adapter.
CSS prefixes Tree
Common namespace ConfigProvider and local prefixCls; the state of the component is preserved when the name is changed.
<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}>{("Common prefix Tree suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Local prefix Tree")}</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={("Tree with prefix")} treeData={[
{
key: 'project', title: "Project", children: [
{ key: 'docs', title: "Documentation" }, { key: 'examples', title: "Examples" }
]
}
]} />
<output
aria-label={("Tree marks with prefix")}
>{checkedKeys.join(', ')}</output>
</div>
</ConfigProvider>
<output aria-label={("CSS prefix Tree")}>{("General: ")}{prefix}{("; local: ")}{(localPrefix
|| ("from the provider"))}</output>
<p>
{("Nodes, switcher, checkbox and lines use the tree prefix. DOM, ARIA IDs, selected keys and unfinished loading are preserved. TreeSelect has its own tree adapter.")}
</p>
</div>
Ctrl, Meta and Shift preserve selection without expanding by title. The switcher button and keyboard work independently.
Expand by title
click, doubleClick and disabled title expansion; selection and expansion are controlled separately.
<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={("Expand by title")} />
<Flex gap="small" wrap>
<output aria-label="expandedKeys">{expanded.join(', ') || '—'}</output>
<output aria-label="selectedKeys">{selected.join(', ') || '—'}</output>
</Flex>
</Flex>
<p>
{("Ctrl, Meta and Shift preserve selection without expanding by title. The switcher button and keyboard work independently.")}
</p>
A normal click selects one file, Ctrl/Meta toggles selection, and Shift selects a visible range. Clicking again preserves selection.
File tree
DirectoryTree, Ctrl/Meta selection and Shift ranges.
<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={("File tree")} />
<output aria-label={("Selected files")}>{selected.join(', ') || '—'}</output>
<p>
{("A normal click selects one file, Ctrl/Meta toggles selection, and Shift selects a visible range. Clicking again preserves selection.")}
</p>
A node switcherIcon takes precedence over the shared icon and loading indicator. Hover callbacks also run for disabled nodes.
Node icons and hover callbacks
Node switcherIcon, showLeafIcon snippet and hovering a disabled node.
<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 icons and hover")} />
<output aria-label={("Hovered node")}>{hovered}</output>
<p>
{("A node switcherIcon takes precedence over the shared icon and loading indicator. Hover callbacks also run for disabled nodes.")}
</p>
createTree reads current data and fieldNames through getters. Replace references to update the model; an unknown key returns an empty path. The model does not scroll the DOM.
Tree data paths
createTree/getPath, data replacement and fieldNames changes without a DOM ref.
<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 path data")}
/>
<Flex gap="small" wrap>
<Button onclick={() => { moved = !moved; }}>{("Move node")}</Button>
<Button onclick={() => {
fields = fields.key === 'id' ? {
key: 'caption',
title: 'caption',
children: 'nodes'
} : { key: 'id', title: 'caption', children: 'nodes' };
}}>{("Change key field")}</Button>
</Flex>
<output aria-label="getPath">{path.map(entity => String(entity.key)).join(' / ') || '—'}</output>
</Flex>
<p>
{("createTree reads current data and fieldNames through getters. Replace references to update the model; an unknown key returns an empty path. The model does not scroll the DOM.")}
</p>
fieldNames maps id/caption/nodes without converting data. TreeEventNode contains the canonical key and state; selectedNodes preserves original records and their payload.
Typed tree schema
Tree and DirectoryTree with fieldNames, payload and canonical event state.
<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={("Tree with typed data")} />
{:else}
<Tree treeData={data} fieldNames={fields} titleRender={title} {icon} showIcon defaultExpandAll
onSelect={record} aria-label={("Tree with typed data")} />
{/if}
<output aria-label={("Tree event data")}>{result}</output>
<p>
{("fieldNames maps id/caption/nodes without converting data. TreeEventNode contains the canonical key and state; selectedNodes preserves original records and their payload.")}
</p>
<style>
.settings { margin-block-end: 12px; }
output {
display: block;
margin-block-start: 12px;
overflow-wrap: anywhere;
}
</style>
Root, item, itemIcon, itemTitle and itemSwitcher accept classes and CSS strings. Local values extend the provider; a nested tree={} replaces its complete configuration. Styling changes preserve selection.
Semantic slots Tree
ConfigProvider.tree, local styling callbacks, nested configuration reset and composite 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}>{("Local Tree styling")}</Checkbox>
<Checkbox bind:checked={reset}>{("Empty provider configuration")}</Checkbox>
<Checkbox bind:checked={directory}>DirectoryTree</Checkbox>
<Button
onclick={() => { alternate = !alternate; }}
>{("Change Tree styling")}</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={("Tree with semantic slots")} />
{:else}
<Tree treeData={data} showIcon defaultExpandAll selectedKeys={selected} onSelect={select}
classNames={local ? classes : undefined} styles={local ? appearance : undefined}
aria-label={("Tree with semantic slots")} />
{/if}
</ConfigProvider>
</ConfigProvider>
<output
aria-label={("Styled tree selection")}
>{selected.join(', ') || '—'}</output>
<p>
{("Root, item, itemIcon, itemTitle and itemSwitcher accept classes and CSS strings. Local values extend the provider; a nested tree={} replaces its complete configuration. Styling changes preserve selection.")}
</p>
<style>.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
} output {
display: block;
margin-block-start: 12px;
}</style>
The model contains 1000 files; the virtual viewport only mounts the required rows. Selection keys persist outside the window. Virtual=undefined inherits the provider; virtual=false renders all rows with native scrolling.
Tree and DirectoryTree virtualization
1000 files, both axes, RTL, measured rows, virtual settings and TreeRef lifecycle.
<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 virtualization")}</Checkbox>
<Checkbox bind:checked={localOff}>{("Local virtual=false")}</Checkbox>
<Checkbox bind:checked={variable}>{("Variable row heights")}</Checkbox>
<Checkbox
bind:checked={measuredOffset}
>{("Offset by the first row height")}</Checkbox>
<Checkbox bind:checked={mounted}>{("Show the virtual tree")}</Checkbox>
</div>
<div class="controls">
<InputNumber
aria-label={("Row key or index")}
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 })}>
{("Back to the start")}
</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; }}
>{("Save TreeRef")}</Button>
<Button
disabled={!saved}
onclick={() => { saved?.scrollTo(0); saved?.focus(); saved?.blur(); }}
>{("Call the saved 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={("Virtual file tree")} />
{/if}
</div>
</ConfigProvider>
<output
aria-label={("Virtual tree selection")}
>{selected.join(', ') || '—'}</output>
<output aria-label="TreeRef nativeElement">{element?.tagName ?? '—'}</output>
<output aria-label="Tree onScroll">{Math.round(top)}</output>
<p>
{("The model contains 1000 files; the virtual viewport only mounts the required rows. Selection keys persist outside the window. Virtual=undefined inherits the provider; virtual=false renders all rows with native scrolling.")}
</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 finds ancestors, the owner updates expandedKeys, and TreeRef.scrollTo runs after tick. AutoExpand only adds the target key in uncontrolled mode; it does not automatically expand all ancestors.
Scroll to a nested node
createTree/getPath finds ancestors; the owner expands the path before 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={("Nested node key")}
bind:value={target}
style="width:180px"
/>
<Button disabled={!tree} onclick={reveal}>{("Expand the path and scroll")}</Button>
<Button disabled={!tree} onclick={reset}>{("Collapse the tree")}</Button>
</div>
<Tree treeData={data} height={210} expandedKeys={expanded} onExpand={keys => { expanded = keys; }}
bind:this={tree} aria-label={("Scroll to a nested node")} />
<output aria-label={("Scroll path")}>{model.getPath(target).map(entity => String(
entity.key
)).join(' / ') || '—'}</output>
<p>
{("createTree finds ancestors, the owner updates expandedKeys, and TreeRef.scrollTo runs after tick. AutoExpand only adds the target key in uncontrolled mode; it does not automatically expand all ancestors.")}
</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
Thirteen ant.design 6.7.0 topics are mapped to the public Svelte API. DirectoryTree, virtualization, scrollTo, createTree/getPath, drag-and-drop and collapse motion are available.
| Theme | Example or limitation |
|---|---|
| Basic | checkable, disabled and initial keys. |
| Controlled Tree | Expand and multiple choice. |
| draggable | Move data in onDrop, allowDrop, RTL and a virtual window. |
| load data asynchronously | Error, retry, loadedKeys and cleanup. |
| Searchable | Highlighting and revealing parents in the example model. |
| Tree with line | showLine and showLeafIcon: a boolean or snippet. |
| Customize Icon | Snippet with TreeEventNode. |
| directory | DirectoryTree and title expansion with expandAction. |
| Customize collapse/expand icon | switcherIcon and expanded from TreeEventNode. |
| Virtual scroll | A virtual viewport, both axes and RTL; virtual=false enables native mode. |
| Scroll to nested node | TreeRef.scrollTo and ancestor expansion with createTree/getPath. |
| Block Node | Full line width. |
| Custom semantic dom styling | Five semantic slots, callbacks and ConfigProvider.tree. |
Tree
| Property | Description | Type | Default |
|---|---|---|---|
draggable | boolean, a raw-node predicate or {nodeDraggable,icon}; icon=false hides the handle. | TreeDraggable<Data> | false |
allowDrop | Checks raw dragNode/dropNode data and relative position -1/0/1, including immediately before drop. | TreeAllowDrop<Data> | — |
onDragStart | Starts HTML5 dragging with the native event and node state. | (info: TreeDragInfo<Data>) => void | — |
onDragEnter | Entering a target; expandedKeys precede delayed expansion, and onExpand receives the new keys. | (info: TreeDragEnterInfo<Data>) => void | — |
onDragOver | Updates the drop position. | (info: TreeDragInfo<Data>) => void | — |
onDragLeave | Leaves a drop target. | (info: TreeDragInfo<Data>) => void | — |
onDragEnd | Ends dragging and releases resources. | (info: TreeDragInfo<Data>) => void | — |
onDrop | The owner moves treeData. dropPosition is the sibling index plus -1/0/1; dropToGap distinguishes dropping inside. | (info: TreeDropInfo<Data>) => void | — |
motion | Custom CSS phases, async prepare and a deadline; false disables transitions, null/undefined enable the default. | TreeMotionConfig | false | null | collapse |
prefixCls | Full CSS prefix of the component and its parts. A non-empty local prop takes precedence; empty string and undefined inherit ConfigProvider. The namespace of the topic is set separately. | string | ConfigProvider.prefixCls + "-tree" |
treeData | Typed original data with stable unique keys. | readonly Data[] | [] |
fieldNames | Key, title and child data field names; supported by Tree and DirectoryTree. | TreeFieldNames | key/title/children |
classNames | Classes for root/item/itemIcon/itemTitle/itemSwitcher: a record or callback receiving props. | TreeSemanticValue<TreeClassNames, Data> | — |
styles | CSS strings for five semantic slots: a record or callback receiving props. | TreeSemanticValue<TreeStyles, Data> | — |
expandedKeys | Controlled deployment; updated in onExpand. | readonly TreeKey[] | internal state |
defaultExpandedKeys | Initial opening. | readonly TreeKey[] | [] |
defaultExpandAll | Expand source data during initialization. | boolean | false |
autoExpandParent | Reveal parents controlled keys. | boolean | false |
defaultExpandParent | Expand parents on initialization. | boolean | true |
expandAction | Title expansion; a modified click only changes selection. | false | "click" | "doubleClick" | false |
selectedKeys | Controlled row selection. | readonly TreeKey[] | internal state |
defaultSelectedKeys | Initial row selection. | readonly TreeKey[] | [] |
multiple | Multiple Choice Tree. | boolean | false |
selectable | Allow row selection. | boolean | true |
checkable | Show checkbox. | boolean | false |
checkStrictly | Independent marks of parents and children. | boolean | false |
checkedKeys | Controlled marks; in strict mode the object is checked/halfChecked. | readonly TreeKey[] | TreeCheckedKeys | internal state |
defaultCheckedKeys | Initial marks. | readonly TreeKey[] | [] |
loadData | Loading children. The owner updates treeData. | (node: TreeEventNode) => PromiseLike<unknown> | — |
loadedKeys | Controlled set of loaded branches; updated in onLoad. | readonly TreeKey[] | internal state |
onExpand | Request for disclosure. | (keys, {expanded, node, nativeEvent}) => void | — |
onSelect | Select and selectedNodes. | (keys, info) => void | — |
onCheck | Checks, halfCheckedKeys and checkedNodes. | (keys, TreeCheckInfo) => void | — |
onLoad | Download completed successfully. | (keys, {event, node}) => void | — |
filterTreeNode | Match highlighting; does not delete rows. | (node: TreeEventNode) => boolean | — |
titleRender | Your own node text. | Snippet<[Data]> | title field from fieldNames |
showLine | Connecting lines. | boolean | {showLeafIcon: boolean | Snippet<[TreeEventNode]>} | false |
showIcon | Show node icon or general icon. | boolean | false |
icon | General icon. | Snippet<[TreeEventNode]> | — |
switcherIcon | Shared switcher icon; loading takes precedence. | Snippet<[TreeEventNode]> | standard |
switcherLoadingIcon | Loading icon. | Snippet<[TreeEventNode]> | loading |
blockNode | Row width by container. | boolean | false |
height | Viewport height; undefined/0 render all expanded rows without a height constraint. | number | — |
virtual | A virtual window when height is set; false keeps all rows in the DOM. | boolean | ConfigProvider.virtual ?? true |
itemHeight | Estimated height before measurement; zero disables the virtual window. | number | Tree tokens |
scrollWidth | Virtual content width for horizontal scrolling. | number | — |
itemScrollOffset | Offset for automatic scrolling of the active node. | number | 0 |
onScroll | Holder scroll event; native onscroll is also supported. | (event: UIEvent) => void | — |
tabIndex | The tree's position in keyboard focus order. The tabindex attribute takes precedence. | number | 0 |
onFocus | The tree gains focus after resolving the active node. | (event: FocusEvent) => void | — |
onBlur | The tree loses focus. | (event: FocusEvent) => void | — |
onKeyDown | A key press after the tree handles it. | (event: KeyboardEvent) => void | — |
onMouseDown | A mouse button press before focus moves. | (event: MouseEvent) => void | — |
onContextMenu | The tree's context menu event after the node's onRightClick. | (event: MouseEvent) => void | — |
activeKey | Controlled active keyboard node. | TreeKey | null | internal state |
onMouseEnter | Hovering row content, including disabled nodes. | ({event, node}) => void | — |
onMouseLeave | Leaving row content with the current TreeEventNode. | ({event, node}) => void | — |
onActiveChange | Change the active node. | (key: TreeKey | null) => void | — |
TreeDataNode
| Property | Description | Type | Default |
|---|---|---|---|
key | Unique stable identifier. | string | number | bigint | is required |
title | Available node name. | TreeTitleContent<TreeDataNode> | --- |
children | Child nodes. | readonly TreeDataNode[] | — |
isLeaf | Leaf attribute; false allows the branch to be loaded. | boolean | by children/loadData |
disabled | Node shutdown and mark distribution boundary. | boolean | false |
disableCheckbox | Disable only checkbox. | boolean | false |
checkable | Show the checkbox of this node. | boolean | general checkable |
selectable | Allow selection of this node. | boolean | general selectable |
switcherIcon | The node icon takes precedence over the shared renderer and loading indicator. | Snippet<[TreeEventNode]> | shared switcherIcon |
icon | Node icon. | Snippet<[TreeEventNode]> | general icon |
class | Node string class. | string | — |
style | CSS node strings. | string | — |
TreeTitleContent supports strings, numbers, nested arrays and snippets receiving the original node; boolean/null/undefined render nothing. Icon and titleRender preserve Data types. bind:nativeElement returns the outer root; bind:this provides TreeRef with focus/blur/scrollTo. height defines a virtual viewport; virtual=false retains native scrolling.
DirectoryTree inherits TreeProps; its defaults are expandAction="click", showIcon=true and blockNode=true. Multiple selection uses Ctrl/Meta and Shift.
createTree(dataOrGetter, config).getPath(key) returns TreeDataEntity[]: node, nodes, key, pos, index, level, parent and children. The model, Tree and DirectoryTree support the same fieldNames mapping; payload conversion is not required.
TreeRef methods
TreeRef for Tree and DirectoryTree provides focus(options?), blur() and scrollTo(config?). nativeElement remains a separate bindable prop and clears on unmount.
TreeScrollConfig accepts a number, {top,left}, a key or an index with align=top/bottom/auto and offset. offset is a number or a pure TreeScrollOffset function with getSize(startKey,endKey?). An unknown key leaves the position unchanged; null/undefined show the scrollbar.
left is a nonnegative logical position in RTL as well. autoExpand on a key request only adds the target key to uncontrolled expandedKeys, without expanding ancestors or calling onExpand. After unmount, a saved ref safely stops performing actions.
Semantic DOM
Five semantic slots are available through classNames/styles and ConfigProvider.tree. Values are records or callbacks receiving props; CSS uses strings. role=tree uses aria-activedescendant; treeitem reports level, selection, checked and expanded states.
| Element | Purpose |
|---|---|
root | Outer tree root; the ordinary style keeps precedence. |
item | Node row; data class/style is supplemented by semantic styling. |
itemIcon | Node icon area. |
itemTitle | Title area, including snippets and nested content. |
itemSwitcher | Switcher button or leaf area. |
| Element | Purpose |
|---|---|
.ant-tree | External root, class/style and nativeElement. |
.ant-tree-list | Focusable role=tree with aria-activedescendant. |
.ant-tree-list-holder | Virtual or native scroll viewport. |
.ant-tree-treenode | role=treeitem with statuses and level. |
.ant-tree-switcher | Expand button excluded from Tab order. |
.ant-tree-checkbox | Button role=checkbox. |
.ant-tree-node-content-wrapper | Line selection button. |
.ant-tree-iconEle | Icon area. |
.ant-tree-list-holder-inner | Mounted virtual rows; their position follows scrolling. |
.ant-tree-list-scrollbar-vertical | Vertical virtual scrollbar; positioned on the left in RTL. |
.ant-tree-list-scrollbar-horizontal | Horizontal scrollbar when scrollWidth exceeds the viewport width. |
.ant-tree-title | Name used as available name. |
Registration tokens
Tree tokens control row height, switcher size, indentation and state colors. The example switches themes without resetting selection and preserves RTL. Directory tokens set the colors of selected DirectoryTree rows.
| Token | Purpose |
|---|---|
titleHeight | Row height. |
switcherSize | Opening width. |
indentSize | Horizontal nesting step. |
nodeHoverBg | Hover background. |
nodeHoverColor | Hover-text. |
nodeSelectedBg | Background of the selected node. |
nodeSelectedColor | Text of the selected node. |
directoryNodeSelectedBg | Selected DirectoryTree row background. |
directoryNodeSelectedColor | Selected DirectoryTree row text. |
| Token | Meaning |
|---|---|
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
Row selection and marking are one state?
selectedKeys controls selection, checkedKeys controls checkmarks, and expandedKeys controls expansion. Accept them via onSelect, onCheck and onExpand separately.
How does checkStrictly work?
If false, parents and children are connected and can receive partial marks. If true, the checks are independent, and onCheck returns checked/halfChecked.
Why didn't defaultExpandAll expand the loaded nodes?
Initial props have already been read. For later data, update expandedKeys or create a tree after loading.
Does filterTreeNode hide non-matching rows?
No, it highlights the nodes. Parent disclosure, separate data filtering and text highlighting are organized by the application.
Is there virtualization and scrollTo?
Yes. A positive height and enabled virtual define a virtual viewport. TreeRef.scrollTo accepts coordinates, a key or an index; the owner handles ancestor expansion.
How do I enable dragging and motion?
draggable enables dragging, but the owner updates treeData in onDrop. Default motion is already enabled; motion=false disables it. The examples above demonstrate both modes.
How to control from the keyboard?
Use arrows, Home/End, Enter and Space. The focus remains on the tree; activeKey reports the active node separately from selection and checkmarks.