Demos
How to import
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
</script>
Basic Usage
By default, tree is in single select mode and each item is selectable.
- 亚洲
- 中国
- 北京
- 上海
- 北美洲
Code
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: '亚洲',
value: 'Asia',
key: '0',
children: [
{
label: '中国',
value: 'China',
key: '0-0',
children: [
{
label: '北京',
value: 'Beijing',
key: '0-0-0',
},
{
label: '上海',
value: 'Shanghai',
key: '0-0-1',
},
],
},
],
},
{
label: '北美洲',
value: 'North America',
key: '1',
},
];
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree defaultExpandAll {style} {treeData} />Multi-choice
You could use multiple to set mode to multi-choice. When all child items are selected, the parent item will be selected.
- Asia
- China
- Beijing
- Shanghai
- Chengdu
- Japan
- Osaka
- North America
- United States
- Canada
Code
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{ label: 'Beijing', value: 'Beijing', key: '0-0-0' },
{ label: 'Shanghai', value: 'Shanghai', key: '0-0-1' },
{ label: 'Chengdu', value: 'Chengdu', key: '0-0-2' },
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [{ label: 'Osaka', value: 'Osaka', key: '0-1-0' }],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{ label: 'United States', value: 'United States', key: '1-0' },
{ label: 'Canada', value: 'Canada', key: '1-1' },
],
},
];
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree defaultExpandAll multiple {style} {treeData} />Searchable
Use filterTreeNode to support search input. By default it searches the label property of the data. You can use treeNodeFilterProp to set another property to search or pass in a function to filterTreeNode to customize search behavior.
You could also use showFilteredOnly if you prefer to display filtered results only.
- Asia
- North America
Code
<script lang="ts">
import { Switch, Tree } from '@fibrae/semi-ui-svelte';
let showFilteredOnly = $state(false);
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{ label: 'Beijing', value: 'Beijing', key: '0-0-0' },
{ label: 'Shanghai', value: 'Shanghai', key: '0-0-1' },
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [{ label: 'Osaka', value: 'Osaka', key: '0-1-0' }],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{ label: 'United States', value: 'United States', key: '1-0' },
{ label: 'Canada', value: 'Canada', key: '1-1' },
],
},
];
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<span id="tree-searchable-filtered-only">showFilteredOnly</span>
<Switch aria-labelledby="tree-searchable-filtered-only" bind:checked={showFilteredOnly} size="small" />
<br />
<Tree filterTreeNode multiple {showFilteredOnly} {style} {treeData} />After setting the filterTreeNode property to enable search, you can customize the search box with the search snippet, whose arguments are class, value, placeholder, showClear and onChange. search={false} hides the search box.
- Asia
- North America
Code
<script lang="ts">
import { Input, Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{ label: 'Beijing', value: 'Beijing', key: '0-0-0' },
{ label: 'Shanghai', value: 'Shanghai', key: '0-0-1' },
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [{ label: 'Osaka', value: 'Osaka', key: '0-1-0' }],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{ label: 'United States', value: 'United States', key: '1-0' },
{ label: 'Canada', value: 'Canada', key: '1-1' },
],
},
];
</script>
<Tree filterTreeNode {treeData}>
{#snippet search({ class: searchClass, value, placeholder, showClear, onChange })}
<Input class={searchClass} {onChange} {placeholder} {showClear} {value}>
{#snippet prefix()}Search{/snippet}
</Input>
{/snippet}
</Tree>Trigger search manually
Use bind:this to get the Tree instance, and call its search method to trigger search manually. Note that you need to set filterTreeNode to enable search at the same time. If the search box is outside the Tree, you can hide the search box inside it with search={false}.
- Asia
- North America
Code
<script lang="ts">
import { Input, Tree, type TreeHandle } from '@fibrae/semi-ui-svelte';
let tree = $state<TreeHandle>();
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{ label: 'Beijing', value: 'Beijing', key: '0-0-0' },
{ label: 'Shanghai', value: 'Shanghai', key: '0-0-1' },
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [{ label: 'Osaka', value: 'Osaka', key: '0-1-0' }],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{ label: 'United States', value: 'United States', key: '1-0' },
{ label: 'Canada', value: 'Canada', key: '1-1' },
],
},
];
</script>
<div>
<Input aria-label="filter tree" onChange={(value) => tree?.search(value)} showClear>
{#snippet prefix()}Search{/snippet}
</Input>
<div style="margin-top: 20px">搜索结果如下:</div>
<Tree bind:this={tree} blockNode={false} filterTreeNode search={false} {treeData} />
</div>JSON TreeData
You could use treeDataSimpleJson to pass in treeNodes data in JSON format. In this case, key will be used as key and label, and value will be used as value correspondingly. Return value includes JSON data in selected nodes.
- Node1
- Node2
Code
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
const json = {
Node1: {
'Child Node1': '0-0-1',
'Child Node2': '0-0-2',
},
Node2: '0-1',
};
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree multiple onChange={(value) => console.log('当前所有选中项: ', value)} onSelect={(key) => console.log('当前选项: ', key)} {style} treeDataSimpleJson={json} />BlockNode
You could use blockNode to set node to display as a row. In this case, styles for hovering and selected state take effects on the entire row. By default, it is set to true. When it is set to false, only label will be highlighted.
- Asia
- China
- Beijing
- Shanghai
- Japan
- North America
- Asia
- China
- Beijing
- Shanghai
- Japan
- North America
Code
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{
label: 'Beijing',
value: 'Beijing',
key: '0-0-0',
},
{
label: 'Shanghai',
value: 'Shanghai',
key: '0-0-1',
},
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [
{
label: 'Osaka',
value: 'Osaka',
key: '0-1-0',
},
],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{
label: 'United States',
value: 'United States',
key: '1-0',
},
{
label: 'Canada',
value: 'Canada',
key: '1-1',
},
],
},
];
</script>
<div>
<Tree blockNode={false} {treeData} value="Shanghai" />
<br />
<Tree blockNode={false} multiple {treeData} value="Shanghai" />
</div>Custom TreeNode Label
The label of TreeNodeData accepts only a string or a number. Custom node content comes from the label snippet, whose arguments are item (the node data), label and searchWord (the current search word). Search by filterTreeNode still matches the label text in treeData.
Node content is best kept for display. Buttons and links in a node can be reached with Tab (see Accessibility), but screen readers read them as part of the node's name and arrow-key browsing skips them. Put actions on a node outside the tree, for example in a menu opened by onContextMenu or in a toolbar next to the tree.
- 亚洲大洲
Code
<script lang="ts">
import { Tag, Tree } from '@fibrae/semi-ui-svelte';
// Node content is display-only: focus stays on the tree, so buttons and links inside are keyboard-unreachable
const treeData = [
{
label: '亚洲',
value: 'yazhou',
key: 'yazhou',
children: [
{
label: '中国',
value: 'zhongguo',
key: 'zhongguo',
},
{
label: '日本',
value: 'riben',
key: 'riben',
},
],
},
];
const labelStyle = 'display: flex; justify-content: space-between; align-items: center';
const treeStyle = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree style={treeStyle} {treeData}>
{#snippet label({ item, label })}
<div style={labelStyle}>
<span>{label}</span>
<Tag size="small">{item.children ? '大洲' : '国家'}</Tag>
</div>
{/snippet}
</Tree>Ellipsis for long labels. Truncate overlong text with an ellipsis inside the label snippet.
- 亚洲亚洲亚洲亚洲亚洲亚洲亚洲亚洲亚洲亚洲亚洲亚洲
Code
<script lang="ts">
import { Tree, TypographyText } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: '亚洲亚洲亚洲亚洲亚洲亚洲亚洲亚洲亚洲亚洲亚洲亚洲',
value: 'yazhou',
key: 'yazhou',
children: [
{
label: '中国中国中国中国中国中国中国中国中国中国中国中国',
value: 'zhongguo',
key: 'zhongguo',
},
{
label: '日本日本日本日本日本日本日本日本日本日本日本日本',
value: 'riben',
key: 'riben',
},
],
},
];
const treeStyle = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree style={treeStyle} {treeData}>
{#snippet label({ label })}
<TypographyText ellipsis={{ showTooltip: true }} style="width: 100%">{label}</TypographyText>
{/snippet}
</Tree>Custom Icon
Use the icon snippet to add a customized icon. Its arguments are item, level, expanded, isLeaf, loading, selected, checked and halfChecked, so the icon can differ by node. TreeNodeData has no icon field.
- Asia
Code
<script lang="ts">
import { IconMapPin } from '@fibrae/semi-icons-svelte';
import { Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
},
],
},
];
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree {style} {treeData}>
{#snippet icon()}
<IconMapPin style="color: var(--semi-color-text-2)" />
{/snippet}
</Tree>Directory
You could use directory to display tree as a directory with default icons. Also, the icon could be overwritten by custom Icon.
- Asia
- North America
Code
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{
label: 'Beijing',
value: 'Beijing',
key: '0-0-0',
},
{
label: 'Shanghai',
value: 'Shanghai',
key: '0-0-1',
},
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [
{
label: 'Osaka',
value: 'Osaka',
key: '0-1-0',
},
],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{
label: 'United States',
value: 'United States',
key: '1-0',
},
{
label: 'Canada',
value: 'Canada',
key: '1-1',
},
],
},
];
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree directory {style} {treeData} />Disabled
You can use disableStrictly to set whether to enable strict disabling. After enabling strict disabling, when the node is disabled, the selected state cannot be changed through the relationship between the child or the parent.
- Asia
- China
- Beijing
- Shanghai
- Japan
- North America
Code
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{
label: 'Beijing',
value: 'Beijing',
key: '0-0-0',
disabled: true,
},
{
label: 'Shanghai',
value: 'Shanghai',
key: '0-0-1',
disabled: true,
},
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [
{
label: 'Osaka',
value: 'Osaka',
key: '0-1-0',
},
],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{
label: 'United States',
value: 'United States',
key: '1-0',
},
{
label: 'Canada',
value: 'Canada',
key: '1-1',
},
],
},
];
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree disableStrictly multiple {style} {treeData} value="Shanghai" />Checked RelationShip
Version: >= 2.5.0
When multiple selections are made, checkRelation can be used to set the type of node selection relationship, optional: 'related' (default), 'unRelated'. When the selection relationship is 'unRelated', it means that selections between nodes do not affect each other.
- Asia
- China
- Beijing
- Shanghai
- Chengdu
- Japan
- Osaka
- North America
- United States
- Canada
Code
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{
label: 'Beijing',
value: 'Beijing',
key: '0-0-0',
},
{
label: 'Shanghai',
value: 'Shanghai',
key: '0-0-1',
},
{
label: 'Chengdu',
value: 'Chengdu',
key: '0-0-2',
},
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [
{
label: 'Osaka',
value: 'Osaka',
key: '0-1-0',
},
],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{
label: 'United States',
value: 'United States',
key: '1-0',
},
{
label: 'Canada',
value: 'Canada',
key: '1-1',
},
],
},
];
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree checkRelation="unRelated" defaultExpandAll multiple {style} {treeData} />Default Expand All
Both defaultExpandAll and expandAll can set the default expanded/collapsed state of Tree. The difference between the two is that defaultExpandAll only takes effect at initialization, while expandAll will not only take effect at initialization, but also when the data (treeData/treeDataSimpleJson) is dynamically updated, expandAll will still take effect.
Among them, expandAll is supported starting from 1.30.0.
In the demo below, after clicking the button to update TreeData, defaultExpandAll becomes invalid, and expandAll still takes effect.
- Node1
- Child Node1
- Child Node2
- Node2
- Node1
- Child Node1
- Child Node2
- Node2
Code
<script lang="ts">
import { Button, Tree, type TreeProps } from '@fibrae/semi-ui-svelte';
const json = {
Node1: {
'Child Node1': '0-0-1',
'Child Node2': '0-0-2',
},
Node2: '0-1',
};
const json2 = {
Node3: {
'Child Node1': '0-0-1',
'Child Node2': '0-0-2',
'Child Node3': '0-0-3',
'Child Node4': '0-0-4',
},
Node2: '0-1',
};
const style = 'margin-right: 20px; width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
let tree = $state<TreeProps['treeDataSimpleJson']>(json);
</script>
<Button style="margin-bottom: 10px" onclick={() => (tree = json2)}>点击更新 TreeData</Button>
<div style="display: flex">
<div>
<span>defaultExpandAll</span>
<Tree defaultExpandAll {style} treeDataSimpleJson={tree} />
</div>
<div>
<span>expandAll</span>
<Tree expandAll {style} treeDataSimpleJson={tree} />
</div>
</div>Controlled Expansion with Search
Bind the expanded nodes with bind:expandedKeys, or use it along with onExpand. bind:expandedKeys={get, set} makes the expansion fully controlled; unbound, the given expandedKeys is only the initially expanded nodes. When the expansion is controlled, if you enable filterTreeNode and search, the node will not be automatically expanded. At this time, the expansion of the node is completely controlled by expandedKeys. You can use the second parameter filteredExpandedKeys of onSearch to realize the search expansion effect when the expansion is controlled.
- 亚洲
- 北美洲
Code
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
let expandedKeys = $state<string[]>([]);
const treeData = [
{
label: '亚洲',
value: 'Asia',
key: '0',
children: [
{
label: '中国',
value: 'China',
key: '0-0',
children: [
{
label: '北京',
value: 'Beijing',
key: '0-0-0',
},
{
label: '上海',
value: 'Shanghai',
key: '0-0-1',
},
],
},
{
label: '日本',
value: 'Japan',
key: '0-1',
},
],
},
{
label: '北美洲',
value: 'North America',
key: '1',
},
];
const handleSearch = (_inputValue: string, filteredExpandedKeys: string[]) => {
expandedKeys = [...filteredExpandedKeys];
};
</script>
<Tree bind:expandedKeys filterTreeNode onSearch={handleSearch} style="width: 300px" {treeData} />Controlled Component
Bind value with bind:value, or use it along with onChange. bind:value={get, set} makes it fully controlled. Unbound, the given value is only the initial selection.
- 亚洲
- 中国
- 北京
- 上海
- 北美洲
Code
<script lang="ts">
import { Tree, type TreeValue } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: '亚洲',
value: 'Asia',
key: '0',
children: [
{
label: '中国',
value: 'China',
key: '0-0',
children: [
{
label: '北京',
value: 'Beijing',
key: '0-0-0',
},
{
label: '上海',
value: 'Shanghai',
key: '0-0-1',
},
],
},
],
},
{
label: '北美洲',
value: 'North America',
key: '1',
},
];
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
let value = $state<TreeValue>('Shanghai');
</script>
<Tree bind:value {style} {treeData} />Auto Expand Parent
In the case of controlled expansion, when autoExpandParent is turned on, if you want to collapse the parent element, you need to collapse all its child elements. By default, autoExpandParent is false, that is, the collapse of the parent element is not affected by the child element.
- 亚洲
- 中国
- 北京
- 上海
- 北美洲
Code
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: '亚洲',
value: 'Asia',
key: '0',
children: [
{
label: '中国',
value: 'China',
key: '0-0',
children: [
{
label: '北京',
value: 'Beijing',
key: '0-0-0',
},
{
label: '上海',
value: 'Shanghai',
key: '0-0-1',
},
],
},
],
},
{
label: '北美洲',
value: 'North America',
key: '1',
},
];
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
let expandedKeys = $state(['0', '0-0']);
</script>
<div>需要先将“中国”节点收起后,才能够收起“亚洲”节点</div>
<br />
<Tree autoExpandParent bind:expandedKeys {style} {treeData} />Custom expansion icon
The expansion Icon can be customized through the expandIcon snippet, whose arguments are onClick, class and expanded. Put class and onclick on the element it renders.
<Tree {treeData}>
{#snippet expandIcon({ expanded, onClick, class: className })}
{#if expanded}
<IconMinus class={className} onclick={onClick} />
{:else}
<IconPlus class={className} onclick={onClick} />
{/if}
{/snippet}
</Tree>
Examples are as follows:
expandIcon 是固定的图标
- 亚洲
- 中国
- 日本
- 北美洲
expandIcon 随展开状态变化
- 亚洲
- 中国
- 日本
- 北美洲
Code
<script lang="ts">
import { IconChevronDown, IconMinus, IconPlus } from '@fibrae/semi-icons-svelte';
import { Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: '亚洲',
key: 'yazhou',
children: [
{
label: '中国',
key: 'zhongguo',
children: [
{
label: '北京',
key: 'beijing',
},
{
label: '上海',
key: 'shanghai',
},
],
},
{
label: '日本',
key: 'riben',
},
],
},
{
label: '北美洲',
key: 'beimeizhou',
},
];
const style = 'width: 260px; height: 200px; border: 1px solid var(--semi-color-border)';
</script>
<p>expandIcon 是固定的图标</p>
<Tree expandedKeys={['yazhou']} multiple {style} {treeData}>
{#snippet expandIcon()}
<IconChevronDown class="testCls" size="small" />
{/snippet}
</Tree>
<br />
<p>expandIcon 随展开状态变化</p>
<Tree expandedKeys={['yazhou']} multiple {style} {treeData}>
{#snippet expandIcon({ expanded, onClick, class: className })}
{#if expanded}
<IconMinus class={className} size="small" onclick={onClick} />
{:else}
<IconPlus class={className} size="small" onclick={onClick} />
{/if}
{/snippet}
</Tree>Tree with line
Set the line between nodes through showLine, the default is false, supported starting from 2.50.0
- parent-0
- leaf-0-0
- leaf-0-0-0
- leaf-0-0-1
- leaf-0-0-2
- leaf-0-1
- parent-1
Code
<script lang="ts">
import { Switch, Tree } from '@fibrae/semi-ui-svelte';
let show = $state(true);
const treeData = [
{
label: 'parent-0',
key: 'parent-0',
children: [
{
label: 'leaf-0-0',
key: 'leaf-0-0',
children: [
{ label: 'leaf-0-0-0', key: 'leaf-0-0-0' },
{ label: 'leaf-0-0-1', key: 'leaf-0-0-1' },
{ label: 'leaf-0-0-2', key: 'leaf-0-0-2' },
],
},
{ label: 'leaf-0-1', key: 'leaf-0-1' },
],
},
{ label: 'parent-1', key: 'parent-1' },
];
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<div style="display: flex; align-items: center; column-gap: 5px; margin-bottom: 5px">
<strong id="tree-line-show-line">showLine </strong>
<Switch aria-labelledby="tree-line-show-line" bind:checked={show} />
</div>
<Tree defaultExpandAll showLine={show} {style} {treeData} />Virtualized Tree
If you need to render large sets of tree structured data, you could use virtualized tree. In virtualized mode, animation / motion is disabled for better performance.
The property virtualize is an object consisting of the following values:
- height: Height of the tree, If passed in as a string, computed height should not be zero for render purpose, in other words, parent node should have offsetHeight
- width: Width of the tree.
- itemSize: Height for each line of treeNode, required
If tree is searchable, you could also turn on showFilteredOnly to reduce time of rendering for results.
Code
<script lang="ts">
import { Button, Tree, type TreeNodeData } from '@fibrae/semi-ui-svelte';
const style = 'width: 260px; border: 1px solid var(--semi-color-border)';
const virtualize = {
// A set Tree height fills the remaining space
height: 300,
itemSize: 28,
};
const generateData = (x = 5, y = 4, z = 3, data: TreeNodeData[] = []) => {
// x: nodes per level. y: nodes with children per level. z: depth (0 is one level)
const fill = (level: number, preKey: string, nodes: TreeNodeData[]) => {
const parents: string[] = [];
for (let i = 0; i < x; i++) {
const key = `${preKey}-${i}`;
nodes.push({ label: `${key}-标签`, key: `${key}-key`, value: `${key}-value` });
if (i < y) {
parents.push(key);
}
}
if (level < 0) {
return;
}
parents.forEach((key, index) => {
const children: TreeNodeData[] = [];
nodes[index].children = children;
fill(level - 1, key, children);
});
};
fill(z, '0', data);
let total = 0;
for (let n = z + 1; n >= 0; n--) {
total += x * y ** n;
}
return { gData: data, total };
};
let gData = $state.raw<TreeNodeData[]>([]);
let total = $state(0);
const onGen = () => {
const data = generateData();
gData = data.gData;
total = data.total;
};
</script>
<div style="padding: 0 20px">
<Button onclick={onGen}>生成数据:</Button>
<span>共 {total} 个节点</span>
<br />
<br />
{#if gData.length}
<Tree filterTreeNode showFilteredOnly {style} treeData={gData} {virtualize} />
{/if}
</div>Dynamic Update of Data
treeData is replaced as a whole: only a new array updates the tree, while changes made in place to the array or a node are not seen. Declare the data with $state.raw and assign a new array after changing it.
- item-0
Code
<script lang="ts">
import { Button, Tree, type TreeNodeData } from '@fibrae/semi-ui-svelte';
const style = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
let treeData = $state.raw<TreeNodeData[]>([
{
key: '0',
label: 'item-0',
value: '0',
},
]);
const add = () => {
const itemLength = Math.floor(Math.random() * 5) + 1;
treeData = Array.from({ length: itemLength }).map((_, i) => {
const length = Math.floor(Math.random() * 3);
const children = Array.from({ length }).map((_, ci) => ({
key: `${i}-${ci}`,
label: `Leaf-${i}-${ci}`,
value: `${i}-${ci}`,
}));
return {
key: `${i}`,
label: `Item-${i}`,
value: `${i}`,
children,
};
});
};
</script>
<div {style}>
<Tree {treeData} />
<br />
<Button style="margin: 20px" onclick={add}>动态改变数据</Button>
</div>Load Data Asynchronously
You could use loadData to load treeData asynchronously on node expansion. Notice isLeaf is required to mark node as leaf in treeData.
- Expand to load
- Expand to load
- Leaf Node
Code
<script lang="ts">
import { Tree, type TreeNodeData } from '@fibrae/semi-ui-svelte';
let treeData = $state.raw<TreeNodeData[]>([
{ label: 'Expand to load', value: '0', key: '0' },
{ label: 'Expand to load', value: '1', key: '1' },
{ label: 'Leaf Node', value: '2', key: '2', isLeaf: true },
]);
const updateTreeData = (list: TreeNodeData[], key: string | undefined, children: TreeNodeData[]): TreeNodeData[] => {
return list.map((node) => {
if (node.key === key) {
return { ...node, children };
}
if (node.children) {
return { ...node, children: updateTreeData(node.children, key, children) };
}
return node;
});
};
const onLoadData = (treeNode?: TreeNodeData) => {
const key = treeNode?.key;
return new Promise<void>((resolve) => {
if (treeNode?.children) {
resolve();
return;
}
setTimeout(() => {
treeData = updateTreeData(treeData, key, [
{ label: 'Child Node', key: `${key}-0` },
{ label: 'Child Node', key: `${key}-1` },
]);
resolve();
}, 1000);
});
};
</script>
<Tree loadData={onLoadData} {treeData} />Draggable Tree
You could use draggable along with onDrop to achieve a draggable Tree.
The argument of each drag callback is one object with the following fields:
- onDragEnd: { event, node: TreeDragNode }
- onDragEnter: { event, node: TreeDragNode, expandedKeys?: string[] }
- onDragLeave: { event, node: TreeDragNode }
- onDragOver: { event, node: TreeDragNode }
- onDragStart: { event, node: TreeDragNode }
- onDrop: { event, node: TreeDragNode, dragNode: TreeDragNode, dragNodesKeys: string[], dropPosition: number, dropToGap: boolean }
The data type TreeDragNode, in addition to all the attributes of TreeNodeData, also includes expanded and pos attributes,
TreeDragNode {
expanded: boolean,
pos: string
value?: string | number;
label?: string | number;
disabled?: boolean;
isLeaf?: boolean;
[key: string]: any;
}
posrefers to the positional relationship of the current node in the entire treeData, such as the 0th node of the 2nd node of the 1st node of the 0th layer: '0-1-2-0'dropPositionrefers to the position where the dragged node is dropped in the current hierarchy. If it is inserted before the 0th node of the same level, it will be -1, and after the 0th node, it will be 1, and it will fall on it. is 0, and so on. With dropToGap, a more complete judgment can be obtained.dropToGaprefers to whether the dragged node is dropped between nodes, if false, it is dropped above a node
- Asia
- North America
- Europe
Code
<script lang="ts">
import { Tree, type TreeNodeData, type TreeOnDragProps } from '@fibrae/semi-ui-svelte';
type LoopCallback = (item: TreeNodeData, ind: number, arr: TreeNodeData[]) => void;
let treeData = $state.raw<TreeNodeData[]>([
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{
label: 'Beijing',
value: 'Beijing',
key: '0-0-0',
},
{
label: 'Shanghai',
value: 'Shanghai',
key: '0-0-1',
},
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [
{
label: 'Osaka',
value: 'Osaka',
key: '0-1-0',
},
],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{
label: 'United States',
value: 'United States',
key: '1-0',
},
{
label: 'Canada',
value: 'Canada',
key: '1-1',
},
],
},
{
label: 'Europe',
value: 'Europe',
key: '2',
},
]);
const onDrop = (info: TreeOnDragProps) => {
const { dropToGap, node, dragNode } = info;
const dropKey = node.key;
const dragKey = dragNode.key;
const dropPos = node.pos.split('-');
const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
const data = [...treeData];
const loop = (data: TreeNodeData[], key: string | undefined, callback: LoopCallback) => {
data.forEach((item, ind, arr) => {
if (item.key === key) return callback(item, ind, arr);
if (item.children) return loop(item.children, key, callback);
});
};
let dragObj: TreeNodeData = {};
loop(data, dragKey, (item, ind, arr) => {
arr.splice(ind, 1);
dragObj = item;
});
if (!dropToGap) {
loop(data, dropKey, (item) => {
item.children = item.children || [];
item.children.push(dragObj);
});
} else if (dropPosition === 1 && node.children && node.expanded) {
// Expanded with children and dropped in the bottom gap: insert at the top
loop(data, dropKey, (item) => {
item.children = item.children || [];
item.children.unshift(dragObj);
});
} else {
let dropNodeInd = 0;
let dropNodePosArr: TreeNodeData[] = [];
loop(data, dropKey, (_item, ind, arr) => {
dropNodePosArr = arr;
dropNodeInd = ind;
});
if (dropPosition === -1) {
dropNodePosArr.splice(dropNodeInd, 0, dragObj);
} else {
dropNodePosArr.splice(dropNodeInd + 1, 0, dragObj);
}
}
treeData = data;
};
</script>
<Tree draggable {onDrop} {treeData} />Advanced FullRender
v>=1.7.0
You could use the fullLabel snippet for advanced rendering to render the content of the entire row on your own.
The row element (li) carrying the id, role="treeitem" and the row state is provided by Tree itself, and so is the positioning style of a virtualized tree; the snippet holds only what is inside the row. Bind the class argument to the content element and it gets the same indentation, selection and focus styles and the same inline padding as a built-in row. The keyboard is handled by Tree, so a click inside the row is only a pointer shortcut.
The snippet argument types are as follows:
type TreeFullLabelSnippetProps = {
/* The original data of the row */
data: TreeNodeData;
/* The level of the line can be used to customize the indentation value */
level: number;
/* Class name, including built-in styles such as indentation, selection, focus and drag state */
class: string;
/* The built-in expand button, rendered with {@render expandIcon()} */
expandIcon: Snippet;
/* Selected state */
checkStatus: {
/* Whether to select in the multi-select state */
checked: boolean;
/* Whether to half-select in the multi-select state */
halfChecked: boolean;
};
/* Expand status */
expandStatus: {
/* Has it been expanded */
expanded: boolean;
/* Is it unfolding */
loading: boolean;
};
/* Whether the node meets the search conditions */
filtered: boolean;
/* Current search box input */
searchWord: string;
/* Click the callback of the entire row: selects it, or checks it in a multiple tree */
onClick: (event: MouseEvent) => void;
/* Multi-select click callback */
onCheck: (event: MouseEvent) => void;
/* expand callback */
onExpand: (event: MouseEvent) => void;
/* Right-click the callback for the entire row */
onContextmenu: (event: MouseEvent) => void;
/* Double-click the entire line of callback */
onDblclick: (event: MouseEvent) => void;
};
<Tree {treeData}>
{#snippet fullLabel({ data, class: className, onClick })}
<div class={className} onclick={onClick} role="presentation">{data.label}</div>
{/snippet}
</Tree>
Here are some demos.
First is to render Parent node as separator and only allow leaf nodes to be selected.
fullLabel only takes care of the UI rendering and won't affect inside data logic. But you could choose info to your needs and use it with controlled mode for advanced usage.
- Asia
- North America
Code
<script lang="ts">
import { Checkbox, Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{
label: 'Beijing',
value: 'Beijing',
key: '0-0-0',
},
{
label: 'Shanghai',
value: 'Shanghai',
key: '0-0-1',
},
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [
{
label: 'Osaka',
value: 'Osaka',
key: '0-1-0',
},
],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{
label: 'United States',
value: 'United States',
key: '1-0',
},
{
label: 'Canada',
value: 'Canada',
key: '1-1',
},
],
},
];
const treeStyle = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree leafOnly multiple style={treeStyle} {treeData}>
<!-- Focus stays on the tree (arrows expand, Enter/Space check), so the inline checkbox is display-only -->
{#snippet fullLabel({ class: cls, data, checkStatus, expandIcon, onCheck, onExpand })}
<div class={cls} role="presentation" onclick={data.children?.length ? onExpand : onCheck}>
{#if data.children?.length}
{@render expandIcon()}
{:else}
<Checkbox aria-hidden="true" checked={checkStatus.checked} indeterminate={checkStatus.halfChecked} style="margin-right: 8px" tabindex={-1} />
{/if}
<span>{data.label}</span>
</div>
{/snippet}
</Tree>The second is for the scenario of "I hope that only leaf nodes can be single-selected, and the parent node only plays a role in grouping".
- You only need to click on the parent node without triggering the selection, click on the leaf node to trigger.
- Asia
- North America
Code
<script lang="ts">
import { Tree } from '@fibrae/semi-ui-svelte';
const treeData = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
children: [
{ label: 'Beijing', value: 'Beijing', key: '0-0-0' },
{ label: 'Shanghai', value: 'Shanghai', key: '0-0-1' },
],
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
children: [{ label: 'Osaka', value: 'Osaka', key: '0-1-0' }],
},
],
},
{
label: 'North America',
value: 'North America',
key: '1',
children: [
{ label: 'United States', value: 'United States', key: '1-0' },
{ label: 'Canada', value: 'Canada', key: '1-1' },
],
},
];
const treeStyle = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree onChange={(value) => console.log('change', value)} style={treeStyle} {treeData}>
{#snippet fullLabel({ class: rowClass, data, expandIcon, onClick, onExpand })}
<div class={rowClass} role="presentation" onclick={data.children?.length ? onExpand : onClick}>
{@render expandIcon()}
<span>{data.label}</span>
</div>
{/snippet}
</Tree>Third is for the scenario when selecting Parent node also highlighting child node.
- 黑色固定按钮
- 模块
- 可自由摆放的组件
- 分栏容器
- 按钮组件
- 按钮组件
- 模块
- 自定义组件
Code
<script lang="ts">
import type { Component } from 'svelte';
import { IconAbsoluteStroked, IconComponentStroked, IconFixedStroked, IconInnerSectionStroked, IconSectionStroked } from '@fibrae/semi-icons-svelte';
import { Tree, type TreeNodeData } from '@fibrae/semi-ui-svelte';
const icons: Record<string, Component<{ style?: string }>> = {
'fix-btn-0': IconFixedStroked,
'module-0': IconSectionStroked,
'free-compo-0': IconAbsoluteStroked,
'split-col-0': IconInnerSectionStroked,
'btn-0': IconComponentStroked,
'btn-1': IconComponentStroked,
'module-1': IconSectionStroked,
'cus-0': IconComponentStroked,
};
const iconStyle = 'margin-right: 8px; color: var(--semi-color-text-2)';
let selected = $state.raw(new Set<string | undefined>());
let selectedThroughParent = $state.raw(new Set<string | undefined>());
const treeData = [
{
label: '黑色固定按钮',
key: 'fix-btn-0',
},
{
label: '模块',
key: 'module-0',
children: [
{
label: '可自由摆放的组件',
key: 'free-compo-0',
},
{
label: '分栏容器',
key: 'split-col-0',
children: [
{
label: '按钮组件',
key: 'btn-0',
},
{
label: '按钮组件',
key: 'btn-1',
},
],
},
],
},
{
label: '模块',
key: 'module-1',
children: [
{
label: '自定义组件',
key: 'cus-0',
},
],
},
];
const findDescendantKeys = (node: TreeNodeData) => {
const res = [node.key];
const findChild = (item?: TreeNodeData) => {
if (!item) return;
const { children } = item;
if (children && children.length) {
children.forEach((child) => {
res.push(child.key);
findChild(child);
});
}
};
findChild(node);
return res;
};
const onSelect = (key: string, _selected: boolean, node: TreeNodeData) => {
selected = new Set([key]);
selectedThroughParent = new Set(findDescendantKeys(node));
};
const rowBackground = (key: string | undefined) => {
if (selected.has(key)) return 'var(--semi-blue-0)';
if (selectedThroughParent.has(key)) return 'rgb(from var(--semi-blue-0) r g b / .5)';
return 'transparent';
};
const treeStyle = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree defaultExpandAll {onSelect} style={treeStyle} {treeData}>
{#snippet fullLabel({ class: cls, data, expandIcon, onClick })}
{@const Icon = icons[data.key ?? '']}
<!-- the tree handles the keyboard: the row is a pointer shortcut -->
<div class={cls} role="presentation" style:background-color={rowBackground(data.key)} onclick={onClick}>
{#if !data.children?.length}
<span style="width: 24px"></span>
{:else}
{@render expandIcon()}
{/if}
<Icon style={iconStyle} />
<span>{data.label}</span>
</div>
{/snippet}
</Tree>Advanced FullRender with Draggable
Draggable (draggable) and advanced customization (fullLabel) can be used at the same time.
- 黑色固定按钮
- 模块
- 可自由摆放的组件
- 分栏容器
- 按钮组件
- 按钮组件
- 模块
- 自定义组件
Code
<script lang="ts">
import type { Component } from 'svelte';
import { IconAbsoluteStroked, IconComponentStroked, IconFixedStroked, IconSectionStroked } from '@fibrae/semi-icons-svelte';
import { Tree, type TreeNodeData, type TreeOnDragProps } from '@fibrae/semi-ui-svelte';
type LoopCallback = (item: TreeNodeData, ind: number, arr: TreeNodeData[]) => void;
const icons: Record<string, Component<{ style?: string }>> = {
'fix-btn-0': IconFixedStroked,
'module-0': IconSectionStroked,
'free-compo-0': IconAbsoluteStroked,
'split-col-0': IconSectionStroked,
'btn-0': IconComponentStroked,
'btn-1': IconComponentStroked,
'module-1': IconSectionStroked,
'cus-0': IconComponentStroked,
};
const iconStyle = 'margin-right: 8px; color: var(--semi-color-text-2)';
let selected = $state.raw(new Set<string | undefined>());
let selectedThroughParent = $state.raw(new Set<string | undefined>());
let treeData = $state.raw<TreeNodeData[]>([
{
label: '黑色固定按钮',
key: 'fix-btn-0',
},
{
label: '模块',
key: 'module-0',
children: [
{
label: '可自由摆放的组件',
key: 'free-compo-0',
},
{
label: '分栏容器',
key: 'split-col-0',
children: [
{
label: '按钮组件',
key: 'btn-0',
},
{
label: '按钮组件',
key: 'btn-1',
},
],
},
],
},
{
label: '模块',
key: 'module-1',
children: [
{
label: '自定义组件',
key: 'cus-0',
},
],
},
]);
const onDrop = (info: TreeOnDragProps) => {
const { dropToGap, node, dragNode } = info;
const dropKey = node.key;
const dragKey = dragNode.key;
const dropPos = node.pos.split('-');
const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
const data = [...treeData];
const loop = (data: TreeNodeData[], key: string | undefined, callback: LoopCallback) => {
data.forEach((item, ind, arr) => {
if (item.key === key) return callback(item, ind, arr);
if (item.children) return loop(item.children, key, callback);
});
};
let dragObj: TreeNodeData = {};
loop(data, dragKey, (item, ind, arr) => {
arr.splice(ind, 1);
dragObj = item;
});
if (!dropToGap) {
loop(data, dropKey, (item) => {
item.children = item.children || [];
item.children.push(dragObj);
});
} else if (dropPosition === 1 && node.children && node.expanded) {
loop(data, dropKey, (item) => {
item.children = item.children || [];
item.children.unshift(dragObj);
});
} else {
let dropNodeInd = 0;
let dropNodePosArr: TreeNodeData[] = [];
loop(data, dropKey, (_item, ind, arr) => {
dropNodePosArr = arr;
dropNodeInd = ind;
});
if (dropPosition === -1) {
dropNodePosArr.splice(dropNodeInd, 0, dragObj);
} else {
dropNodePosArr.splice(dropNodeInd + 1, 0, dragObj);
}
}
treeData = data;
};
const findDescendantKeys = (node: TreeNodeData) => {
const res = [node.key];
const findChild = (item?: TreeNodeData) => {
if (!item) return;
const { children } = item;
if (children && children.length) {
children.forEach((child) => {
res.push(child.key);
findChild(child);
});
}
};
findChild(node);
return res;
};
const onSelect = (key: string, _selected: boolean, node: TreeNodeData) => {
selected = new Set([key]);
selectedThroughParent = new Set(findDescendantKeys(node));
};
const rowBackground = (key: string | undefined) => {
if (selected.has(key)) return 'var(--semi-blue-0)';
if (selectedThroughParent.has(key)) return 'rgb(from var(--semi-blue-0) r g b / .5)';
return 'transparent';
};
const treeStyle = 'width: 260px; height: 420px; border: 1px solid var(--semi-color-border)';
</script>
<Tree defaultExpandAll draggable {onDrop} {onSelect} style={treeStyle} {treeData}>
{#snippet fullLabel({ class: cls, data, expandIcon, onClick })}
{@const Icon = icons[data.key ?? '']}
<!-- the tree handles the keyboard: the row is a pointer shortcut -->
<div class={cls} role="presentation" style:background-color={rowBackground(data.key)} onclick={onClick}>
{#if !data.children?.length}
<span style="width: 24px"></span>
{:else}
{@render expandIcon()}
{/if}
<Icon style={iconStyle} />
<span>{data.label}</span>
</div>
{/snippet}
</Tree>API Reference
Tree
Props
| Property | Description | Type | Default |
|---|---|---|---|
| autoExpandParent | Whether the parents of the nodes in expandedKeys expand automatically when expandedKeys changes; they always do on mount. When on, a controlled tree collapses a parent only after its expanded children are collapsed. | boolean | false |
| autoExpandWhenDragEnter | Whether dragging over a collapsed node expands it. | boolean | true |
| autoMergeValue | When a parent is selected the value leaves out its descendants; applies when leafOnly is false. | boolean | true |
| blockNode | Shows each node as a whole row, highlighting the row on hover and selection; when off only the label is highlighted. | boolean | true |
| checkRelation | How the checked states of nodes relate in a multiple tree: related links parents and children, unRelated keeps them independent. | CheckRelation | "related" |
| defaultExpandAll | Expands every node on mount. Later changes of treeData or treeDataSimpleJson do not affect it; use expandAll for that. | boolean | false |
| directory | Directory mode with built-in folder icons, which the icon snippet can replace. | boolean | false |
| disabled | Disables the whole tree. A node with disabled: false does not lift it. | boolean | false |
| disableStrictly | Strict disabling: a disabled node cannot change state through the selection of its parent or children. | boolean | false |
| draggable | Whether nodes can be dragged, used together with onDrop. It cannot be combined with virtualize. | boolean | false |
| emptyContent | Content shown when there are no nodes, or when the search finds none with showFilteredOnly on. | Snippet | - |
| expandAction | How a node expands: false only through the arrow, click on a click, doubleClick on a double click. The keyboard does not use it. | ExpandAction | false |
| expandAll | Expands every node, and keeps doing so when the data changes. | boolean | false |
| expandedKeys | Expanded nodes, bindable with bind:expandedKeys. Unbound, the given value is only the initially expanded nodes, showing their direct children. bind:expandedKeys={get, set} makes expansion fully controlled. | string[] | - |
| expandIcon | The expand icon, with { onClick, class, expanded } as its argument; put class and onclick on the element it renders. | TypeSnippet<[TreeExpandIconSnippetProps]> | - |
| filterTreeNode | Whether search is on. true matches by treeNodeFilterProp; a function customizes the match, with data as the node. | Typeboolean | ((inputValue: string, treeNodeString: string, data?: TreeNodeData) => boolean) | false |
| fullLabel | Content of the whole row. Its argument holds class, data, level, expandIcon, checkStatus, expandStatus, filtered, searchWord and onClick, onCheck, onExpand, onContextmenu, onDblclick. Tree provides the row element carrying the id, role and state, and virtualized positioning; the snippet holds only what is inside. | TypeSnippet<[TreeFullLabelSnippetProps]> | - |
| hideDraggingNode | Hides the drag image of the node being dragged. | boolean | false |
| icon | A node's icon. Its argument holds item, level, expanded, isLeaf, loading, selected, checked and halfChecked, so it can differ by node; empty output keeps the directory icon. | TypeSnippet<[TreeIconSnippetProps]> | - |
| keyMaps | Custom field names for key, label and value in a node. When label is mapped and search is on, set treeNodeFilterProp to one of the keys in treeData or provide filterTreeNode. | TreeKeyMapProps | - |
| label | Content of a node's label, with { item, label, searchWord } as its argument. Search still matches the label text in treeData. | TypeSnippet<[TreeLabelSnippetProps]> | - |
| labelEllipsis | Whether an overflowing label is truncated; on by default for a virtualized tree. | boolean | - |
| leafOnly | In a multiple tree, the value and the payload of onChange hold leaf nodes only. | boolean | false |
| loadData | Loads the children of a node and returns a Promise. Mark leaves with isLeaf in the data; a node without isLeaf shows the expand arrow while this is set. | Type(treeNode?: TreeNodeData) => Promise<void> | - |
| loadedKeys | Nodes already loaded, used with loadData and bindable with bind:loadedKeys. | string[] | - |
| motion | Whether expanding and collapsing are animated; animation is off for a virtualized tree. | boolean | true |
| multiple | Whether several nodes can be selected. A parent is checked automatically once all its children are. | boolean | false |
| onChange | Called when the selection changes, with the current value. | Type(value: TreeValue) => void | - |
| onChangeWithObject | When true the argument of onChange is the node object with value, label and other fields instead of the value; a controlled value must then be objects with a value. | boolean | false |
| onContextMenu | Called on a right click on a node, with the event and the node data. | Type(event: MouseEvent, node: TreeNodeData) => void | - |
| onDoubleClick | Called on a double click on a node, with the event and the node data. | Type(event: MouseEvent, node: TreeNodeData) => void | - |
| onDragEnd | Called when a drag ends. | Type(info: TreeDragProps) => void | - |
| onDragEnter | Called when a drag enters a node; the argument holds expandedKeys when that expanded a collapsed node. | Type(info: TreeDragEnterProps) => void | - |
| onDragLeave | Called when a drag leaves a node. | Type(info: TreeDragProps) => void | - |
| onDragOver | Called while a drag is over a node. | Type(info: TreeDragProps) => void | - |
| onDragStart | Called when a node starts to be dragged. | Type(info: TreeDragProps) => void | - |
| onDrop | Called when a node is dropped; the argument holds node, dragNode, dragNodesKeys, dropPosition and dropToGap. | Type(info: TreeOnDragProps) => void | - |
| onExpand | Called when a node expands or collapses, with the array of expanded keys and an info object holding expanded and node. | Type(expandedKeys: string[], info: TreeExpandedOtherProps) => void | - |
| onLoad | Called when a node has loaded, with the set of loaded nodes and the node just loaded. | Type(loadedKeys: Set<string>, node: TreeNodeData) => void | - |
| onSearch | Called when the search input changes; filteredExpandedKeys are the nodes expanded by the search or by value, which controlled expansion can use to show the results. | Type(input: string, filteredExpandedKeys: string[]) => void | - |
| onSelect | Called when a node is selected or deselected, with its key, whether it is selected and its data. | Type(selectedKey: string, selected: boolean, node: TreeNodeData) => void | - |
| renderDraggingNode | The element the browser shows while a node is dragged, with the node element nodeInstance and the node data node as arguments; on dragstart the snippet is rendered into a detached container and used as the drag image, so only app-level context reaches it. | TypeSnippet<[TreeDraggingNodeSnippetProps]> | - |
| search | Replaces the search box, with class, value, placeholder, showClear and onChange as its argument; false hides the box while filterTreeNode still filters. | TypeSnippet<[TreeSearchSnippetProps]> | false | - |
| searchClassName | Class of the search box container. | string | - |
| searchPlaceholder | Placeholder of the search box. | string | - |
| searchStyle | Style string of the search box container. | string | - |
| showClear | Whether the search box shows a clear button. | boolean | true |
| showFilteredOnly | Shows only the filtered nodes while searching. | boolean | false |
| showLine | Shows connecting lines between nodes. | boolean | false |
| treeData | Node data; keys are unique across the tree. Only a new array updates the tree, changes made in place are not seen. A node's icon is drawn by the icon snippet, and its label is a string or number. | TreeNodeData[] | - |
| treeDataSimpleJson | Node data as a plain JSON object; the value is a JSON object holding the selected nodes. | TreeDataSimpleJson | - |
| treeNodeFilterProp | The node field matched against the search input, label by default. | string | "label" |
| value | Value of the selected node (its key when it has no value), bindable with bind:value; an array when multiple. Unbound, the given value is only the initial selection; bind:value={get, set} makes it fully controlled. | TreeValue | - |
| virtualize | List virtualization for many nodes: height, width and itemSize (required). Animation is off once enabled. | TreeVirtualize | - |
Methods
| Method | Description | Type |
|---|---|---|
| scrollTo | In a virtualized tree, scrolls an expanded node into view; align is center by default. | Type(scrollData: TreeScrollData) => void |
| search | Searches as if the value were typed into the search box; filterTreeNode must be set. | Type(input: string) => void |
The Svelte Tree has no className property: undeclared attributes such as class, style and data-* land on the root element .semi-tree-wrapper, and aria-* and tabindex land on the role="tree" element. The empty state has no role="tree" element, so aria-* attributes are dropped there.
TreeNodeData
Key for
TreeNodeDatais required and must be unique,labelcan be duplicated. Value is not required; without it, the value property inonChange,valueandonChangeWithObjectpoints to the key property. To ensure everything behave as expected, keep a consistency of whether to have value or not to have value.
| Properties | Instructions | Type | Default |
|---|---|---|---|
| value | Value | string|number | - |
| label | Displayed label; custom content comes from the label snippet | string|number | - |
| disabled | Disabled. When the Tree's disabled is true the whole tree is disabled, and a node's disabled: false does not lift it | boolean | false |
| key | Required and must be unique | string | - |
| isLeaf | Toggle whether node is leaf node, only takes effect in async load data with loadData | boolean | - |
Virtualize Object
itemSizeis required to render virtualized tree。
| Properties | Instructions | Type | Default |
|---|---|---|---|
| height | Height. If passed as a string, computed height should not be 0 for render purpose, in other words, parent node should have offsetHeight | number|string | '100%' |
| itemSize | Height for each line of treeNode, required | number | - |
| width | Width | number|string | '100%' |
Methods
Tree exposes search and scrollTo through bind:this, typed as TreeHandle; see the Methods part of the Tree table above.
<script lang="ts">
import { Tree, type TreeHandle } from '@fibrae/semi-ui-svelte';
let tree = $state<TreeHandle>();
const search = (value: string) => tree?.search(value);
</script>
<Tree bind:this={tree} filterTreeNode {treeData} />
Accessibility
ARIA
- Tree supports passing in
aria-label,aria-labelledbyandaria-describedbyto name and describe the Tree; they are all set on therole="tree"element; - Tree sets
aria-level,aria-setsize,aria-posinsetandaria-disabledon each node, andaria-expandedon nodes that can expand; a single-choice tree marks the selected node witharia-selected, a multi-choice tree marks checked nodes witharia-checked(mixedwhen half checked); - Tree will set
roletotreeandtreeitemfor corresponding parts.
- The content of
fullLabelis wrapped in Tree's ownli, which carries theid,role="treeitem"and the states above.
- The expand arrow and the checkbox in front of a node only picture its state: they are hidden from screen readers and take no focus.
Keyboard Interaction
Tree follows the WAI-ARIA Tree View pattern: the whole tree is one Tab stop, focus stays on the tree, aria-activedescendant points at the current node, and the current node shows the focus ring.
ArrowDown,ArrowUp: move to the next or previous visible node;Home,End: move to the first or last visible nodeArrowRight: expand a collapsed node; on an expanded node, move to its first child (swapped withArrowLeftin RTL)ArrowLeft: collapse an expanded node; otherwise move to the parentEnter,Space: select the current node, or check and uncheck it in a multi-choice tree; disabled nodes do not respond- Typing characters: move to the next node whose text starts with them
A node that is selected, checked, expanded, right-clicked or double-clicked with the pointer becomes the current node of the keyboard, and the arrow keys continue from it.
The keyboard does not trigger expandAction; the arrow keys expand and collapse.
Buttons and links inside a node (for example a control in the label snippet) can be reached with Tab. While one of them has focus, keys are handled by that control and the tree does not respond.
Demo:
<Tree aria-label="example tree" {treeData} />
Content Guidelines
- Try to use phrases, capitalize the first letter
- Keep the same form of terminology between levels, such as all place names or country names
Design Tokens
| Sass variable | Value | Usage |
|---|---|---|
| $transition_duration-tree_option-bg | var(--semi-transition_duration-none) | 树选项-背景色-动画持续时间 |
| $transition_function-tree_option-bg | var(--semi-transition_function-easeIn) | 树选项-背景色-过渡曲线 |
| $transition_delay-tree_option-bg | var(--semi-transition_delay-none) | 树选项-背景色-延迟时间 |
| $transform_scale-tree-option | var(--semi-transform_scale-none) | 树选项-放大 |
| $color-tree_option-text-default | var(--semi-color-text-0) | 树选项文字颜色 |
| $color-tree_option-icon-default | var(--semi-color-text-2) | 树选项图标颜色 |
| $color-tree_option-bg-hover | var(--semi-color-fill-0) | 树选项背景色 - 悬停 |
| $color-tree_option_selected-bg-default | var(--semi-color-fill-1) | 树选项背景色 - 按下 |
| $color-tree_option-bg-active | var(--semi-color-primary-light-default) | 树选项背景色 - 选中 |
| $color-tree_option_disabled-text-default | var(--semi-color-disabled-text) | 禁用树选项文字颜色 |
| $color-tree_option-icon-hover | var(--semi-color-text-0) | 树选项图标颜色 - 悬浮 |
| $color-tree_option-icon-active | var(--semi-color-black) | 树选项图标颜色 - 按下 |
| $color-tree_option_loading-icon-default | var(--semi-color-primary) | 树选项加载 spin 颜色 |
| $color-tree_option_draggable_insert-border-default | var(--semi-color-primary) | 树选项加载 spin 颜色 |
| $font-tree_option_hightlight-fontWeight | $font-weight-bold | 树选项高亮文本字重 |
| $color-tree_option_hightlight-text | var(--semi-color-primary) | 树选项高亮文本颜色 |
| $radius-tree_checkbox_addon | var(--semi-border-radius-small) | 多选树 checkbox 圆角 |
| $spacing-tree_search_wrapper-paddingX | 12px | 树搜索框水平内边距 |
| $spacing-tree_search_wrapper-paddingY | 8px | 树搜索框垂直内边距 |
| $spacing-tree_option_level-paddingLeft | 20px | 树选项缩进增量 |
| $spacing-tree_option_level1-paddingLeft | 8px | 树选项最上层左侧内边距 |
| $spacing-tree_optionList-paddingX | 0 | 树选项列表水平内边距 |
| $spacing-tree_optionList-paddingY | 8px | 树选项列表垂直内边距 |
| $spacing-tree_option-paddingTop | 4px | 树选项顶部内边距 |
| $spacing-tree_option-paddingBottom | 4px | 树选项底部内边距 |
| $spacing-tree_icon-marginRight | 8px | 树选项图标右侧外边距 |
| $spacing-tree_label_withIcon-marginRight | 8px | 树选项图标右侧外边距 |
| $spacing-tree_option_draggable-paddingY | 2px | 可拖拽的树选项垂直内边距 |
| $spacing-tree_option_draggable-paddingX | 0 | 可拖拽的树选项水平内边距 |
| $width-tree_emptyIcon | $width-icon-small | 树选项空图标宽度 |
| $width-tree_spinIcon | $width-icon-small | 树选项加载 spin 宽度 |
| $width-tree_option_draggable-border | 2px | 可拖拽的树标示线宽度 |
| $width-tree_option_line | 1px | showline展示线宽度 |