Demos
How to import
import { Tree } from '@fibrous/semi-ui-solid';
Basic Usage
By default, tree is in single select mode and each item is selectable.
Code
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: TreeNodeData[] = [
{
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)',
};
export default function TreeDemo() {
return <Tree treeData={treeData} defaultExpandAll style={style} />;
}Multi-choice
You could use multiple to set mode to multi-choice. When all child items are selected, the parent item will be selected.
Code
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: 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: '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)',
};
export default function TreeDemo() {
return <Tree treeData={treeData} multiple defaultExpandAll style={style} />;
}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.
Code
import { createSignal } from 'solid-js';
import { Switch, Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: 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',
},
],
},
];
const style = {
width: '260px',
height: '420px',
border: '1px solid var(--semi-color-border)',
};
export default function TreeDemo() {
const [showFilteredOnly, setShowFilteredOnly] = createSignal(false);
return (
<>
<span id="tree-searchable-filtered-only">showFilteredOnly</span>
<Switch aria-labelledby="tree-searchable-filtered-only" checked={showFilteredOnly()} onChange={(checked) => setShowFilteredOnly(checked)} size="small" />
<br />
<Tree treeData={treeData} multiple filterTreeNode showFilteredOnly={showFilteredOnly()} style={style} />
</>
);
}After setting the filterTreeNode property to enable search, you can customize the rendering method of the search box by setting searchRender. When set to false, the search box can be hidden. The parameter of searchRender is a live object, read it in the returned JSX and do not destructure it.
Code
import { Input, Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: 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',
},
],
},
];
export default function TreeDemo() {
// spread keeps the live props; the prefix written after it replaces the icon the tree passes
return <Tree filterTreeNode searchRender={(searchProps) => <Input {...searchProps} prefix="Search" />} treeData={treeData} />;
}Trigger search manually
Use the ref of Tree to get its root element, 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 by setting searchRender={false}.
Code
import { Input, Tree, type TreeElement, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: 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',
},
],
},
];
export default function TreeDemo() {
let tree: TreeElement | undefined;
return (
<div>
<Input aria-label="filter tree" prefix="Search" showClear onChange={(v) => tree?.search(v)} />
<div style={{ 'margin-top': '20px' }}>搜索结果如下:</div>
<Tree ref={(element) => (tree = element)} filterTreeNode searchRender={false} treeData={treeData} blockNode={false} />
</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.
Code
import { Tree, type TreeDataSimpleJson } from '@fibrous/semi-ui-solid';
const json: TreeDataSimpleJson = {
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)',
};
export default function TreeDemo() {
return <Tree treeDataSimpleJson={json} multiple onChange={(e) => console.log('当前所有选中项: ', e)} onSelect={(e) => console.log('当前选项: ', e)} style={style} />;
}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.
Code
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: 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',
},
],
},
];
export default function TreeDemo() {
return (
<div>
<Tree treeData={treeData} defaultValue="Shanghai" blockNode={false} />
<br />
<Tree treeData={treeData} defaultValue="Shanghai" multiple blockNode={false} />
</div>
);
}Custom TreeNode Label
The label of TreeNodeData accepts only a string or a number; custom node content comes from renderLabel. renderLabel receives the label, the node data and the search word, and returns the node content; it is called again when one of them changes. Search 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
import { Tag, Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const rowStyle = {
display: 'flex',
'justify-content': 'space-between',
'align-items': 'center',
};
const treeStyle = {
width: '260px',
height: '420px',
border: '1px solid var(--semi-color-border)',
};
export default function TreeDemo() {
const treeData: TreeNodeData[] = [
{
label: '亚洲',
value: 'yazhou',
key: 'yazhou',
children: [
{
label: '中国',
value: 'zhongguo',
key: 'zhongguo',
},
{
label: '日本',
value: 'riben',
key: 'riben',
},
],
},
];
// Node content is display-only: focus stays on the tree, so buttons and links inside are keyboard-unreachable
return (
<Tree
treeData={treeData}
style={treeStyle}
renderLabel={(label, node) => (
<div style={rowStyle}>
<span>{label}</span>
<Tag size="small">{node?.children ? '大洲' : '国家'}</Tag>
</div>
)}
/>
);
}Ellipsis for long labels. Return a Typography.Text with the ellipsis property from renderLabel to truncate overlong text with an ellipsis.
Code
import { Tree, Typography, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeDataWithNode: TreeNodeData[] = [
{
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)',
};
const renderLabel = (label?: string | number) => (
<Typography.Text ellipsis={{ showTooltip: true }} style={{ width: '100%' }}>
{label}
</Typography.Text>
);
export default function TreeDemo() {
return <Tree treeData={treeDataWithNode} renderLabel={renderLabel} style={treeStyle} />;
}Custom Icon
You could use icon to add customized icon. It accepts an element, or a function that is called once per row with the row's props (including its node data) and returns that row's icon; use the function to give nodes different icons. TreeNodeData has no icon field.
Code
import { IconMapPin } from '@fibrous/semi-icons-solid';
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const style = {
width: '260px',
height: '420px',
border: '1px solid var(--semi-color-border)',
};
export default function TreeDemo() {
const treeData: TreeNodeData[] = [
{
label: 'Asia',
value: 'Asia',
key: '0',
children: [
{
label: 'China',
value: 'China',
key: '0-0',
},
{
label: 'Japan',
value: 'Japan',
key: '0-1',
},
],
},
];
return <Tree treeData={treeData} style={style} icon={<IconMapPin style={{ color: 'var(--semi-color-text-2)' }} />} />;
}Directory
You could use directory to display tree as a directory with default icons. Also, the icon could be overwritten by custom Icon.
Code
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: 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',
},
],
},
];
const style = {
width: '260px',
height: '420px',
border: '1px solid var(--semi-color-border)',
};
export default function TreeDemo() {
return <Tree treeData={treeData} directory style={style} />;
}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.
Code
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: TreeNodeData[] = [
{
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)',
};
export default function TreeDemo() {
return <Tree treeData={treeData} defaultValue="Shanghai" multiple disableStrictly style={style} />;
}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.
Code
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: 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: '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)',
};
export default function TreeDemo() {
return <Tree treeData={treeData} multiple checkRelation="unRelated" defaultExpandAll style={style} />;
}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.
Code
import { createSignal } from 'solid-js';
import { Button, Tree, type TreeDataSimpleJson } from '@fibrous/semi-ui-solid';
const json: TreeDataSimpleJson = {
Node1: {
'Child Node1': '0-0-1',
'Child Node2': '0-0-2',
},
Node2: '0-1',
};
const json2: TreeDataSimpleJson = {
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)',
};
export default function TreeDemo() {
const [tree, setTree] = createSignal<TreeDataSimpleJson>(json);
const handleClick = () => {
setTree(json2);
};
return (
<>
<Button onClick={handleClick} style={{ 'margin-bottom': '10px' }}>
点击更新 TreeData
</Button>
<div style={{ display: 'flex' }}>
<div>
<span>defaultExpandAll</span>
<Tree defaultExpandAll treeDataSimpleJson={tree()} style={style} />
</div>
<div>
<span>expandAll</span>
<Tree expandAll treeDataSimpleJson={tree()} style={style} />
</div>
</div>
</>
);
}Controlled Expansion with Search
When expandedKeys is passed in, it is the expanded controlled component, which can be used with onExpand. 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 argument filteredExpandedKeys of onSearch to realize the search expansion effect when the expansion is controlled.
Code
import { createSignal } from 'solid-js';
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: TreeNodeData[] = [
{
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',
},
];
export default function TreeDemo() {
const [expandedKeys, setExpandedKeys] = createSignal<string[]>([]);
return (
<Tree
style={{ width: '300px' }}
treeData={treeData}
filterTreeNode
expandedKeys={expandedKeys()}
onExpand={(keys) => {
setExpandedKeys(keys);
}}
onSearch={(_inputValue, filteredExpandedKeys) => {
setExpandedKeys([...filteredExpandedKeys]);
}}
/>
);
}Controlled Component
When value is passed in, Tree is a controlled component. You can use it along with onChange.
Code
import { createSignal } from 'solid-js';
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: TreeNodeData[] = [
{
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)',
};
export default function TreeDemo() {
const [value, setValue] = createSignal('Shanghai');
return (
<Tree
treeData={treeData}
value={value()}
onChange={(next) => {
if (typeof next === 'string') {
setValue(next);
}
}}
style={style}
/>
);
}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
import { createSignal } from 'solid-js';
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: TreeNodeData[] = [
{
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)',
};
export default function TreeDemo() {
const [expandedKeys, setExpandedKeys] = createSignal<string[]>(['0', '0-0']);
return (
<>
<div>需要先将“中国”节点收起后,才能够收起“亚洲”节点</div>
<br />
<Tree autoExpandParent treeData={treeData} onExpand={(keys) => setExpandedKeys(keys)} expandedKeys={expandedKeys()} style={style} />
</>
);
}Custom expansion icon
The expansion Icon can be customized through expandIcon, which accepts a JSX element or a function. An element automatically gets the class and the click that expands; a function receives onClick, class and expanded, and returns the whole icon. expanded is a live property: read it in the returned JSX and do not destructure it.
expandIcon: JSX.Element | ((props: { onClick: (e: MouseEvent) => void; class: string; expanded: boolean }) => JSX.Element);
Examples are as follows:
expandIcon 是元素
expandIcon 是函数
Code
import { Show } from 'solid-js';
import { IconChevronDown, IconMinus, IconPlus } from '@fibrous/semi-icons-solid';
import { Tree, type TreeExpandIconProps, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: TreeNodeData[] = [
{
label: '亚洲',
key: 'yazhou',
children: [
{
label: '中国',
key: 'zhongguo',
children: [
{
label: '北京',
key: 'beijing',
},
{
label: '上海',
key: 'shanghai',
},
],
},
{
label: '日本',
key: 'riben',
},
],
},
{
label: '北美洲',
key: 'beimeizhou',
},
];
// The tree adds the class and the click to an element, but a function renders the icon itself, so the icon reads
// `expanded` inside Show: a plain `if` would keep the first value
const expandIconFunc = (iconProps: TreeExpandIconProps) => (
<Show when={iconProps.expanded} fallback={<IconPlus size="small" class={iconProps.class} onClick={iconProps.onClick} />}>
<IconMinus size="small" class={iconProps.class} onClick={iconProps.onClick} />
</Show>
);
const style = {
width: '260px',
height: '200px',
border: '1px solid var(--semi-color-border)',
};
export default function TreeDemo() {
return (
<>
<p>expandIcon 是元素</p>
<Tree expandIcon={<IconChevronDown size="small" class="testCls" />} multiple defaultExpandedKeys={['yazhou']} treeData={treeData} style={style} />
<br />
<p>expandIcon 是函数 </p>
<Tree multiple expandIcon={expandIconFunc} defaultExpandedKeys={['yazhou']} treeData={treeData} style={style} />
</>
);
}Tree with line
Set the line between nodes through showLine, the default is false, supported starting from 2.50.0
Code
import { createSignal } from 'solid-js';
import { Switch, Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const treeData: TreeNodeData[] = [
{
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)',
};
export default function TreeDemo() {
const [show, setShow] = createSignal(true);
return (
<>
<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" checked={show()} onChange={(checked) => setShow(checked)} />
</div>
<Tree showLine={show()} defaultExpandAll treeData={treeData} style={style} />
</>
);
}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
import { createSignal, Show } from 'solid-js';
import { Button, Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const style = {
width: '260px',
border: '1px solid var(--semi-color-border)',
};
function 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)
function 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 };
}
export default function TreeDemo() {
const [gData, setGData] = createSignal<TreeNodeData[]>([]);
const [total, setTotal] = createSignal(0);
const onGen = () => {
const data = generateData();
setGData(data.gData);
setTotal(data.total);
};
return (
<div style={{ padding: '0 20px' }}>
<Button onClick={onGen}>生成数据: </Button>
<span>共 {total()} 个节点</span>
<br />
<br />
<Show when={gData().length}>
<Tree
treeData={gData()}
filterTreeNode
showFilteredOnly
style={style}
virtualize={{
// A set Tree height fills the remaining space
height: 300,
itemSize: 28,
}}
/>
</Show>
</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.
Code
import { createSignal } from 'solid-js';
import { Button, Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const style = {
width: '260px',
height: '420px',
border: '1px solid var(--semi-color-border)',
};
export default function TreeDemo() {
const [treeData, setTreeData] = createSignal<TreeNodeData[]>([
{
key: '0',
label: 'item-0',
value: '0',
},
]);
const add = () => {
const itemLength = Math.floor(Math.random() * 5) + 1;
const nextTreeData = Array.from({ length: itemLength }).map((_, i) => {
const length = Math.floor(Math.random() * 3);
const children = Array.from({ length }).map((_child, ci) => {
const child = {
key: `${i}-${ci}`,
label: `Leaf-${i}-${ci}`,
value: `${i}-${ci}`,
};
return child;
});
const item = {
key: `${i}`,
label: `Item-${i}`,
value: `${i}`,
children,
};
return item;
});
setTreeData(nextTreeData);
};
return (
<div style={style}>
<Tree treeData={treeData()} />
<br />
<Button onClick={add} style={{ margin: '20px' }}>
动态改变数据
</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.
Code
import { createSignal } from 'solid-js';
import { Tree, type TreeNodeData } from '@fibrous/semi-ui-solid';
const initialData: 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,
},
];
function 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;
});
}
export default function TreeDemo() {
const [treeData, setTreeData] = createSignal<TreeNodeData[]>(initialData);
function onLoadData(treeNode?: TreeNodeData) {
const key = treeNode?.key;
return new Promise<void>((resolve) => {
if (treeNode?.children) {
resolve();
return;
}
setTimeout(() => {
setTreeData((origin) =>
updateTreeData(origin, key, [
{
label: 'Child Node',
key: `${key}-0`,
},
{
label: 'Child Node',
key: `${key}-1`,
},
])
);
resolve();
}, 1000);
});
}
return <Tree loadData={onLoadData} treeData={treeData()} />;
}Draggable Tree
You could use draggable along with onDrop to achieve a draggable Tree.
The callback arguments of the drag events are objects with the following fields:
- onDragEnd: ({ event, node: TreeDragNode }) => void
- onDragEnter: ({ event, node: TreeDragNode, expandedKeys?: string[] }) => void
- onDragLeave: ({ event, node: TreeDragNode }) => void
- onDragOver: ({ event, node: TreeDragNode }) => void
- onDragStart: ({ event, node: TreeDragNode }) => void
- onDrop: ({ event, node: TreeDragNode, dragNode: TreeDragNode, dragNodesKeys: string[], dropPosition: number, dropToGap: boolean }) => void
The data type TreeDragNode, in addition to all the attributes of TreeNodeData, also includes expanded and pos attributes:
interface TreeDragNode extends TreeNodeData {
expanded: boolean;
pos: string;
}
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
Code
import { createSignal } from 'solid-js';
import { Tree, type TreeNodeData, type TreeOnDragProps } from '@fibrous/semi-ui-solid';
type LoopCallback = (item: TreeNodeData, ind: number, arr: TreeNodeData[]) => void;
export default function TreeDemo() {
const initialData: 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 [treeData, setTreeData] = createSignal<TreeNodeData[]>(initialData);
function 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);
}
}
setTreeData(data);
}
return <Tree treeData={treeData()} draggable onDrop={onDrop} />;
}Advanced FullRender
v>=1.7.0
Tree's API covers most rendering needs. For a very special customization, use renderFullLabel to take over the rendering of the whole row. It is called once per row with a live object: read its fields in the returned JSX and do not destructure it.
The parameter types of renderFullLabel are as follows:
type RenderFullLabelProps = {
/* 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;
/* Creates the built-in expand button; every call creates a new element, so call it where the button goes */
expandIcon: () => JSX.Element;
/* 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: (e: MouseEvent) => void;
/* Multi-select click callback */
onCheck: (e: MouseEvent) => void;
/* Expand callback */
onExpand: (e: MouseEvent) => void;
/* Right-click the callback for the entire row */
onContextMenu: (e: MouseEvent) => void;
/* Double-click the entire row callback */
onDoubleClick: (e: MouseEvent) => void;
};
Tree provides the row element (li) carrying the id, role="treeitem" and the row state, and the content is placed inside it; the positioning style of a virtualized tree is on that element too. Bind the class parameter to the content element and it gets the same indentation, selection and focus styles and the same inline padding as a built-in row.
<Tree treeData={treeData} renderFullLabel={(row) => <div class={row.class}>{row.data.label}</div>} />
Here are some demos.
- You only need to render the Checkbox in front of leaf nodes, clicking a parent node does not select it, and clicking a leaf node does.
- Turning on leafOnly also makes the arguments of
onChangeleaf nodes only.
Note:renderFullLabelonly 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.
Code
import { Show } from 'solid-js';
import { Checkbox, Tree, type TreeNodeData, type TreeRenderFullLabelProps } from '@fibrous/semi-ui-solid';
const isLeaf = (row: TreeRenderFullLabelProps) => !(row.data.children && row.data.children.length);
const renderLabel = (row: TreeRenderFullLabelProps) => (
// Focus stays on the tree (arrows expand, Enter/Space check), so the inline checkbox is display-only
<div class={row.class} onClick={(e) => (isLeaf(row) ? row.onCheck(e) : row.onExpand(e))}>
<Show when={!isLeaf(row)}>{row.expandIcon()}</Show>
<Show when={isLeaf(row)}>
<span aria-hidden="true" style={{ 'margin-right': '8px' }}>
<Checkbox tabIndex={-1} indeterminate={row.checkStatus.halfChecked} checked={row.checkStatus.checked} />
</span>
</Show>
<span>{row.data.label}</span>
</div>
);
const treeData: 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',
},
],
},
];
const treeStyle = {
width: '260px',
height: '420px',
border: '1px solid var(--semi-color-border)',
};
export default function TreeDemo() {
return <Tree treeData={treeData} renderFullLabel={renderLabel} multiple leafOnly style={treeStyle} />;
}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.
Code
import { Tree, type TreeNodeData, type TreeRenderFullLabelProps } from '@fibrous/semi-ui-solid';
const isLeaf = (row: TreeRenderFullLabelProps) => !(row.data.children && row.data.children.length);
const renderLabel = (row: TreeRenderFullLabelProps) => (
<div class={row.class} onClick={(e) => (isLeaf(row) ? row.onClick(e) : row.onExpand(e))}>
{row.expandIcon()}
<span>{row.data.label}</span>
</div>
);
const treeData: 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',
},
],
},
];
const treeStyle = {
width: '260px',
height: '420px',
border: '1px solid var(--semi-color-border)',
};
export default function TreeDemo() {
return <Tree treeData={treeData} renderFullLabel={renderLabel} style={treeStyle} onChange={(...args) => console.log('change', ...args)} />;
}Third is for the scenario when selecting Parent node also highlighting child node.
Code
import { createSignal } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { IconAbsoluteStroked, IconComponentStroked, IconFixedStroked, IconInnerSectionStroked, IconSectionStroked } from '@fibrous/semi-icons-solid';
import { Tree, type TreeNodeData, type TreeRenderFullLabelProps } from '@fibrous/semi-ui-solid';
const icons: Record<string, typeof IconFixedStroked> = {
'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 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 treeStyle = {
width: '260px',
height: '420px',
border: '1px solid var(--semi-color-border)',
};
export default function TreeDemo() {
const [selected, setSelected] = createSignal(new Set<string | undefined>());
const [selectedThroughParent, setSelectedThroughParent] = createSignal(new Set<string | undefined>());
const iconStyle = { 'margin-right': '8px', color: 'var(--semi-color-text-2)' };
const treeData: 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 handleSelect = (key: string, _bool: boolean, node: TreeNodeData) => {
setSelected(new Set([key]));
const descendantKeys = findDescendantKeys(node);
setSelectedThroughParent(new Set(descendantKeys));
};
const backgroundOf = (key?: string) => (selected().has(key) ? 'var(--semi-blue-0)' : selectedThroughParent().has(key) ? 'rgb(from var(--semi-blue-0) r g b / .5)' : 'transparent');
const renderLabel = (row: TreeRenderFullLabelProps) => (
<div class={row.class} onClick={row.onClick} style={{ 'background-color': backgroundOf(row.data.key) }}>
{row.data.children && row.data.children.length ? row.expandIcon() : <span style={{ width: '24px' }} />}
<Dynamic component={icons[row.data.key ?? '']} style={iconStyle} />
<span>{row.data.label}</span>
</div>
);
return <Tree treeData={treeData} renderFullLabel={renderLabel} onSelect={handleSelect} style={treeStyle} defaultExpandAll />;
}Advanced FullRender with Draggable
Draggable (draggable) and advanced customization (renderFullLabel) can be used at the same time.
Code
import { createSignal } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { IconAbsoluteStroked, IconComponentStroked, IconFixedStroked, IconSectionStroked } from '@fibrous/semi-icons-solid';
import { Tree, type TreeNodeData, type TreeOnDragProps, type TreeRenderFullLabelProps } from '@fibrous/semi-ui-solid';
const icons: Record<string, typeof IconFixedStroked> = {
'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,
};
type LoopCallback = (item: TreeNodeData, ind: number, arr: TreeNodeData[]) => void;
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 treeStyle = {
width: '260px',
height: '420px',
border: '1px solid var(--semi-color-border)',
};
export default function TreeDemo() {
const [selected, setSelected] = createSignal(new Set<string | undefined>());
const [selectedThroughParent, setSelectedThroughParent] = createSignal(new Set<string | undefined>());
const iconStyle = { 'margin-right': '8px', color: 'var(--semi-color-text-2)' };
const defaultTreeData: 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 [treeData, setTreeData] = createSignal<TreeNodeData[]>(defaultTreeData);
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);
}
}
setTreeData(data);
};
const handleSelect = (key: string, _bool: boolean, node: TreeNodeData) => {
setSelected(new Set([key]));
const descendantKeys = findDescendantKeys(node);
setSelectedThroughParent(new Set(descendantKeys));
};
const backgroundOf = (key?: string) => (selected().has(key) ? 'var(--semi-blue-0)' : selectedThroughParent().has(key) ? 'rgb(from var(--semi-blue-0) r g b / .5)' : 'transparent');
const renderLabel = (row: TreeRenderFullLabelProps) => (
<div class={row.class} onClick={row.onClick} style={{ 'background-color': backgroundOf(row.data.key) }}>
{row.data.children && row.data.children.length ? row.expandIcon() : <span style={{ width: '24px' }} />}
<Dynamic component={icons[row.data.key ?? '']} style={iconStyle} />
<span>{row.data.label}</span>
</div>
);
return <Tree treeData={treeData()} draggable onDrop={onDrop} renderFullLabel={renderLabel} onSelect={handleSelect} style={treeStyle} defaultExpandAll />;
}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 |
| defaultExpandedKeys | Nodes expanded initially, showing their direct children. | string[] | - |
| defaultValue | The initially selected items, read once on mount. | Value | - |
| directory | Directory mode with built-in folder icons, which icon can replace. | boolean | - |
| 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 with the drag callbacks such as 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; null renders no empty state. | JSX.Element | - |
| 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 (controlled). Passing it makes expansion fully controlled, used with onExpand. | string[] | - |
| expandIcon | Custom expand icon. An element gets the switcher class and the click that expands; a function receives onClick, class and expanded and returns the whole icon. | ExpandIcon | - |
| filterTreeNode | Whether search is on. true matches by treeNodeFilterProp; a function customizes the match, with the node data as its third argument. | Typeboolean | ((inputValue: string, treeNodeString: string, data?: TreeNodeData) => boolean) | false |
| hideDraggingNode | Hides the drag image of the node being dragged. | boolean | - |
| icon | Custom node icon. An element is used for every node; a function is called once per row with the row's props, including its node data, and returns that row's icon. | TypeJSX.Element | ((row: TreeRowProps) => JSX.Element) | - |
| 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. | KeyMapProps | - |
| labelEllipsis | Whether an overflowing label is truncated; on by default for a virtualized tree. | boolean | - |
| leafOnly | In a multiple tree, the value and the argument 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 | Loaded nodes (controlled), used with loadData. | 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 selected value; with onChangeWithObject set to true the argument is the node object. | Type(value: Value) => void | - |
| onChangeWithObject | Whether the other fields of a selected node go to onChange. When true the argument is the node object with value, label and other fields instead of the value; a controlled value and defaultValue 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(e: MouseEvent, node: TreeNodeData) => void | - |
| onDoubleClick | Called on a double click on a node, with the event and the node data. | Type(e: MouseEvent, node: TreeNodeData) => void | - |
| onDragEnd | Called when a drag ends, with { event, node }. | Type(dragProps: DragProps) => void | - |
| onDragEnter | Called when a drag enters a node, with { event, node, expandedKeys }; expandedKeys is set when the drag expanded a collapsed node. | Type(dragEnterProps: DragEnterProps) => void | - |
| onDragLeave | Called when a drag leaves a node, with { event, node }. | Type(dragProps: DragProps) => void | - |
| onDragOver | Called while a drag is over a node, with { event, node }. | Type(dragProps: DragProps) => void | - |
| onDragStart | Called when a node starts to be dragged, with { event, node }. | Type(dragProps: DragProps) => void | - |
| onDrop | Called when a node is dropped, with { event, node, dragNode, dragNodesKeys, dropPosition, dropToGap }. | Type(onDragProps: OnDragProps) => void | - |
| onExpand | Called when a node expands or collapses, with the expanded keys and { expanded, node }. | Type(expandedKeys: string[], expandedOtherProps: ExpandedOtherProps) => void | - |
| onLoad | Called when a node has loaded, with the set of loaded keys and the node data. | Type(loadedKeys?: Set<string>, treeNode?: TreeNodeData) => void | - |
| onSearch | Called when the search input changes, with the search value and the keys expanded by the search or by value and defaultValue; under controlled expansion it can expand the results. | Type(searchValue: 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, selectedNode: TreeNodeData) => void | - |
| ref | The root element, which carries the search and scrollTo methods. | TypeRef<TreeElement> | - |
| renderDraggingNode | The drag image the browser shows while a node is dragged. It receives the node element and the node data, and returns an element. | Type(nodeInstance: HTMLElement, node: TreeNodeData) => HTMLElement | - |
| renderFullLabel | Renders the whole row. Called once per row with a live object: read its fields in the returned JSX instead of destructuring. Put class on the content element; expandIcon is a render function that creates the expand button, called where the button goes; Tree provides the row element (li) with its role and state. | Type(renderFullLabelProps: RenderFullLabelProps) => JSX.Element | - |
| renderLabel | Renders a node's label with the label, the node data and the search word; called again when one of them changes. Search still matches the label text in treeData. | Type(label?: string | number, treeNode?: TreeNodeData, searchWord?: string) => JSX.Element | - |
| searchClassName | Class of the search box container. | string | - |
| searchPlaceholder | Placeholder of the search box. | string | - |
| searchRender | Renders a custom search box from a live object with class, prefix, value, onChange, showClear and placeholder. false hides the search box. | Type((searchRenderProps: SearchRenderProps) => JSX.Element) | false | - |
| searchStyle | Style of the search box container. | JSX.CSSProperties | 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 |
| style | Style of the root element, as an object with kebab-case keys such as 'margin-top' or as a string. | JSX.CSSProperties | string | - |
| treeData | Node data; keys are unique across the tree. Only a new array updates the tree, changes made in place are not seen. | 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. | string | "label" |
| value | Value of the selected node, its key when it has no value (controlled). Passing it makes the tree controlled, used with onChange; an array when multiple. | Value | - |
| virtualize | List virtualization for many nodes: height, width and itemSize (required). Animation is off once enabled. | Virtualize | - |
Methods
| Method | Description | Type |
|---|---|---|
| scrollTo | In a virtualized tree, scrolls an expanded node into view; align is center by default. Other arguments run the native scrollTo. | Type(scrollData: ScrollData) => void |
| search | Searches as if the value were typed into the search box; filterTreeNode must be set. | Type(value: string) => void |
class, style and ref, as well as undeclared native attributes such as data-*, land on the root element .semi-tree-wrapper; aria-* attributes and tabIndex land on the element with role="tree". The empty state has no role="tree" element, so aria-* attributes and tabIndex 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,value,defaultValueandonChangeWithObjectpoints 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 renderLabel | 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
The ref of Tree points at the root element, which carries the search and scrollTo methods, typed as TreeElement; see the Tree table above for their descriptions.
import { Tree, type TreeElement } from '@fibrous/semi-ui-solid';
let tree: TreeElement | undefined;
const search = (value: string) => tree?.search(value);
<Tree ref={(element) => (tree = element)} filterTreeNode treeData={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 returned by
renderFullLabelis 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 renderLabel or renderFullLabel output) 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={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展示线宽度 |