TreeSelect
Selecting tree nodes with search, loading and associated marks.
When to use
TreeSelect selects a department, documentation section, or other entry from a hierarchy. The tree is expanded in one pane, and the value contains the node key. If your application needs the full path and separate level columns, use Cascader.
Pass nested treeData with unique values. The title explains the choice to the person; key can be set separately, but the value of the model is determined by value. For a permanent tree without an input field, Tree is intended.
TreeSelect CSS Prefixes show global ConfigProvider.prefixCls and local prefixCls without resetting state. Control and tags use Select prefix; popup adds the suffix -tree-dropdown. The nested tree preserves the native Tree adapter and its own classes: the local prefix TreeSelect is not equal to Tree.prefixCls.
Data schemas and declarations
Custom schema and flat data maps value/label/children through fieldNames and demonstrates treeDataSimpleMode. Search defaults to the literal value field, so set showSearch.treeNodeFilterProp explicitly for another schema. Selection and filter callbacks receive the original custom fields. Simple mode builds standard children from id/pId; keep the children field name unchanged when combining it with fieldNames. Input data is not mutated.
Declarative nodes use TreeSelect.TreeNode and the named TreeSelectTreeNode. treeData takes precedence over declarations. Strategies are available as TreeSelect.SHOW_PARENT, SHOW_CHILD and SHOW_ALL. Icon and switcherIcon accept content or a snippet with TreeEventNode. class/style, data-* and aria-* apply to the row; styles.popup.item overrides its own style.
Node value
Single returns a string or numeric key. multiple returns an array of keys. With labelInValue, an object with value and label is used instead of a key; treeCheckStrictly enables this format automatically.
| Problem | Setting | Example |
|---|---|---|
| Select one node | treeData, value, onChange |
Selecting a node from treeData |
| Select independent nodes | multiple |
Multiple nodes |
| Tag a branch with descendants | treeCheckable |
Related marks |
| Check the checkbox regardless | treeCheckStrictly |
Independent marks |
| Receive a key along with a signature | labelInValue |
Value with signature |
The managed control receives value and reports a new choice via onChange. Unlike components with bind:value, here the application itself assigns the result to its state. defaultValue specifies the initial local value. Clearing single reports undefined, multiple reports an empty array; the basic example normalizes no selection to null.
The second argument to onChange contains signatures or null in the format labelInValue, the third - triggerValue. This is the key of the node that caused the change, not its parent path. For the path, build a map of the parents using treeData in advance.
Related marks
treeCheckable enables multiple and parent-child relationships. SHOW_CHILD returns the leaf marked nodes, SHOW_PARENT merges the entire branch, SHOW_ALL includes the parent and children. Comparison of strategies shows the difference in results; The strategy affects the model produced, not just the signature.
treeCheckable accepts TreeSelectCheckableContent: boolean, text, numbers, bigint, snippets, nested arrays, iterables and Promise objects. Only JavaScript truthiness is used. false, null, undefined, "", 0, -0, NaN and 0n do not enable checkboxes; [], snippets and Promise objects enable standard checkboxes. The content is not rendered: snippets are not invoked, iterables are not iterated and Promise objects are not awaited.
treeCheckable content compares these flags. The example explicitly enables multiple, so the selected-value array is retained when checkboxes are turned off.
treeCheckStrictly disables the mark association and returns objects with value and label. When changing modes, match the state type to the new format. For regular multiple without checkbox, nodes are selected independently.
selectable=false disables header selection, preserving branch expansion. disabled blocks the node, disableCheckbox specifically disables the checkbox, checkable=false removes its checkbox. The basic example allows you to expand Interface without selecting that heading.
Selection limit
TreeSelect selection limit demonstrates maxCount for multiple, linked checkboxes and treeCheckStrictly. Initial and controlled values are not trimmed when the limit decreases; missing values also count. Selected nodes can still be deselected, and the selection can be cleared after reaching the limit. This limits selection, not the number of visible tags: maxTagCount limits visible tags.
Explicit showCheckedStrategy=SHOW_PARENT disables a nonzero limit. SHOW_ALL disables it without treeCheckStrictly; for plain multiple, do not set this strategy explicitly if you need a limit. SHOW_CHILD and strict mode retain the limit. maxCount=0 prevents new values even with SHOW_PARENT/SHOW_ALL; the limit does not apply to single selection.
With SHOW_CHILD, a parent branch can become unavailable if its direct enabled children exceed the remaining capacity. The final number of values after linked checking is also checked. An attempted selection can call onSelect/onDeselect without onChange if the resulting set exceeds a nonzero limit. Changing maxCount preserves the current selection; switching modes in the example explicitly clears it to align the key and strict object formats.
Title expansion
TreeSelect title expansion demonstrates treeExpandAction=false, click and doubleClick. By default, clicking a title only selects the node. treeExpandedKeys and onTreeExpand control expansion independently of value; changing the mode preserves state.
In click mode, onTreeExpand runs before onChange/onSelect. In multiple mode, a real double click performs two ordinary selection actions before expanding the branch. Ctrl/Meta/Shift suppress title expansion while preserving selection. The switcher, checkbox and keyboard work independently; Enter selects the active node. Explicit isLeaf=true prevents expansion; disabled prevents selection but allows title expansion.
Search and asynchronous branches
showSearch is enabled by default for multiple. To search by title, pass showSearch={{ treeNodeFilterProp: 'title' }}. The same object contains filterTreeNode, searchValue, onSearch and autoClearSearchValue. Search example stores the query separately from the selected node and explicitly clears it after selection.
Closing a single-select control clears its search. For controlled searchValue, accept the empty string in onSearch; the selected node is retained. Closing a multiple-select popup does not clear its query by itself.
Search separators demonstrate tokenSeparators: an array of strings or a (text: string) => string[] function. Splitting clears the query and closes the popup, but does not call onChange or onSelect or select nodes from the typed words. Choose values separately in the tree.
During IME input, splitting waits for compositionend. To paste a list of lines, include \n or \r\n in the separator array or use a function. The function returns the split parts; an empty array or a single unchanged string means no split.
loadData receives the expandable node and returns a Promise. Add the loaded children to treeData before it completes. For a branch that has not yet been loaded, set isLeaf=false, for a leaf node - true. Asynchronous example completes the pending Promise and clears the timer when leaving the page.
loadData is not called during search. For server-side search, handle showSearch.onSearch and update treeData in the application; Don't expect a separate query for each local filter match. treeExpandedKeys and treeLoadedKeys manage expanded and loaded branches separately from the selected value.
Focus and events
TreeSelect focus and events demonstrates showAction=['focus'] and an event log. The popup opens before onFocus. An empty array or ['click'] retains ordinary pointer opening. Changing showAction while the input is already focused does not open the popup on its own. autoFocus and tabIndex set input attributes; native autofocus and tabindex take precedence. During hydration, autofocus preserves focus on another control. As in the original, maxLength does not limit search; native maxlength sets the browser input limit.
Native input onkeydown runs first, followed by onInputKeyDown, internal handling and root onKeyDown. Use event.preventDefault() in native onkeydown to cancel selection or opening. preventDefault in onInputKeyDown does not cancel selection; stopPropagation stops the root callback. Holding Enter selects once until keyup or blur. Space opens a readonly control; Escape closes it. Enter/Space on the clear button does not reach root onKeyDown.
onFocus/onBlur receive actual focusin/focusout events. Root callbacks receive the actual root as currentTarget, a DIV by default; native editor handlers receive an input or textarea. The popup has its own DOM event boundary. Keyboard and outside-pointer closing is deferred until after the root key/blur callback. Server rendering does not run callbacks, autofocus or timers.
The events example lets you switch single/multiple mode and search. Clicking an open single-select control again closes it when search is disabled and keeps it open when search is enabled. In multiple mode, clicking the input keeps the popup open; clicking the field's free area toggles it. Clearing a single-select control with the mouse closes the popup asynchronously; in multiple mode it retains its state. The control's onFocus/onBlur and onClick do not receive popup events, including events from custom content.
Tags and returned labels
Tag display compares numeric and responsive maxTagCount. It limits visible tags; full values remain in callbacks and FormData. maxTagTextLength truncates only string and number labels while preserving the full tooltip text and labels. Snippets and arrays remain opaque content. Responsive tags are measured after mount; server-rendered tags stay hidden until measurement.
tagRender receives TreeSelectTagInfo: render label as a snippet and use closable/onClose for removal. The summary has isMaxTag=true and no value/index/onClose. maxTagPlaceholder receives complete omitted records. With treeTitleRender, the onChange label becomes a bound snippet: it is in labels in raw mode and in the value record with labelInValue/strict, where labels is null. Custom node title saves a snippet and renders it after the control unmounts. Check typeof label === 'function' before rendering; JSON.stringify does not display snippet content.
Control, popup and styling
Control and popup slots demonstrates prefix, suffix and popupRender. suffix receives open, focused, searchValue, showSearch and loading; it takes precedence over suffixIcon, while null/undefined restore icon selection. suffixIcon=null hides the arrow. removeIcon changes the ordinary tag removal icon. allowClear accepts an object with clearIcon and the accessible label. Clearing a nonempty search calls onSearch with an empty string.
FormItem.hasFeedback adds a validation icon beside the default arrow. suffixIcon=null hides the arrow but keeps feedback. A custom suffix replaces this area's content and does not add feedback automatically.
In popupRender, render the supplied menu snippet to retain the original tree. An embedded field can receive focus and retain its draft between popup openings. Semantic styles demonstrates classNames/styles objects and functions. Control slots include root, prefix, input, suffix, clear, content, placeholder, item, itemContent and itemRemove; popup contains root, item, itemTitle and itemSwitcher. Functions receive resolved props. Styles are CSS strings. ConfigProvider.treeSelect sets variant, classNames, styles and switcherIcon; local classes merge with provider classes, while a local popup slot string replaces the matching provider style. A nested provider record replaces the entire parent record.
onPopupVisibleChange, popupStyle, choiceTransitionName and local direction are accepted but have no effect. Use onOpenChange for events, styles.popup.root for styling and ConfigProvider.direction for RTL. Semantic callbacks receive the original values. Native HTML dir remains a separate attribute.
Popup alignment
TreeSelect popup alignment compares popupAlign with builtinPlacements. The former overrides fields of the selected placement; offset, targetOffset and overflow are replaced as whole values. Percentages in offset refer to the popup, while percentages in targetOffset refer to the control.
builtinPlacements replaces the entire map of four placements, including an explicitly empty object. A missing placement uses centering rather than the default entry from the previous map.
ConfigProvider.popupOverflow selects the default map region: the viewport or the scroll document region. The shared example demonstrates inheritance and an explicit viewport. A custom builtinPlacements, including an empty map, replaces the default map; local popupAlign.htmlRegion takes precedence. Changing the shared mode updates the map for the next alignment, retaining the current coordinates.
An open popup retains its calculated alignment until placement changes, the control or popup resizes, the window emits resize or an ancestor scrolls. Replacing the map alone does not recalculate coordinates. Changing popupAlign triggers an immediate recalculation only when the selected entry is absent from the map.
Popup animation
TreeSelect popup animation demonstrates the default transition, a custom CSS name, animation and disabling named motion. transitionName=undefined selects the default slide-up with the ConfigProvider prefix; transitionName="" disables named motion. A nonempty animation takes precedence and forms a name from the Select prefix, -dropdown- and its value.
Provide enter and leave CSS for a custom name; the example uses a fade. Completing the CSS effect completes its phase. A name without CSS receives no artificial completion timer. The popup retains its DOM after leaving, reopening interrupts closing, and multiple search is retained. These options affect the popup rather than tree branch expansion.
theme.token.motion=false disables starting named motion when opening. Changing the setting or name during an active phase does not forcibly complete it.
Custom components
components.root replaces the entire control: default tags, affixes and components.input are not rendered. In the root example, Button displays the selected label and receives ARIA attributes for opening the tree. Removing the root slot restores the default selector with the current value.
components.input replaces only the editor, retaining selector styling, tags and the suffix. The textarea editor demonstrates editor replacement, responsive tags and callback order. Search and selection remain separate data.
With multiple and maxTagCount="responsive", the custom editor participates in tag measurement and its suffix can become absolutely positioned. Resizing the control or editor updates the number of visible tags. The popup retains its anchor during resize and scroll events, including in RTL.
The snippet receives attributes and register. Apply attributes to the actual DOM element and register it with {@attach register}. For a library component, you can register an object with inputElement, nativeElement and focus/blur methods. Use the returned cleanup in $effect; refs are released on replacement or unmount. The Form example forwards attributes to Input, retains TreeSelect as the associated field and does not submit the search as a second form value.
An object of the form { render, props } adds custom attributes. For input, these take priority and custom callbacks run before internal handlers; for root, generated attributes take priority and internal callbacks run first. Apply the merged attributes to retain handlers. Use TreeSelect's native onkeydown to cancel keyboard processing.
The RootElement and EditorElement parameters refine event and ref types. bind:nativeElement returns the current root; bind:inputElement returns an input or textarea, and is absent with a root slot. Removing a slot restores the default div/input. A custom root owns value rendering, ARIA and native restrictions, including disabled.
Virtualization and scrolling
popupMatchSelectWidth matches the control width for true, fits the content for false, or sets a numeric width in px. The control width remains the minimum. An omitted prop or undefined inherits ConfigProvider.popupMatchSelectWidth. Shared popup width compares inheritance with a nested true and a local number on Select.
Large tree contains 600 nodes. virtual inherits ConfigProvider.virtual and defaults to true. listHeight limits the viewport, listItemHeight provides the initial row height estimate, and listItemScrollOffset adds an offset when moving to the active node. popupMatchSelectWidth=false disables virtualization; a numeric value sets popup width. The property inherits ConfigProvider when not set locally.
bind:this exposes TreeSelectRef with focus, blur and scrollTo. The method accepts coordinates or key/index with align and offset. For a branch target, autoExpand expands its internal path if expansion is not specified in props. onPopupScroll receives the tree viewport event. Arrows and Enter continue to operate on the active node; aria-activedescendant points to the row while it is in the DOM.
showScrollBar is accepted as an inherited property, but is not forwarded to the tree and does not affect scrolling. Do not use it to control the TreeSelect scrollbar.
Display and form
treeTitleRender and switcherIcon accept Svelte snippets. Your signatures change the display of a node without changing its value. popupMatchSelectWidth sets the width of the panel, listHeight — the height; for long signatures, check the panel on a narrow screen.
TreeSelect supports virtualization, field schemas, simple mode, tags, popup slots and semantic styles. The supported properties are listed in API.
In subscription form, onChange updates form.setFieldValue and reset restores initialValues. label specifies the available field name. Arrows move focus through the tree, Enter selects a node, Escape closes the popup; focus/blur are accessible through the component instance.
TreeSelect uses design tokens from the current theme for its appearance.
Examples
Selecting a node from treeData
The tree is specified via treeData. Single returns the key of the selected node; parent The interface is expanded but not selected.
<script lang="ts">
import { TreeSelect, type TreeSelectNode, type TreeSelectValue } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
let value = $state<TreeSelectValue>(null);
</script>
<TreeSelect
aria-label={("Basic section")}
{treeData}
{value}
treeDefaultExpandAll
allowClear
placeholder={("Select section")}
onChange={next => { value = next ?? null; }}
/>
<p><output aria-label={("Selected node")}>{JSON.stringify(value)}</output></p>
Multiple nodes
multiple selects nodes independently. The selected labels form tags; removing the tag changes the model.
<script lang="ts">
import { TreeSelect, type TreeSelectNode, type TreeSelectValue } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
let value = $state<TreeSelectValue>(['button']);
</script>
<TreeSelect
aria-label={("Multiple sections")}
{treeData}
{value}
multiple
treeDefaultExpandAll
allowClear
showSearch={{ treeNodeFilterProp: 'title' }}
onChange={next => { value = next; }}
/>
<p><output
aria-label={("Multiple selected nodes")}
>{JSON.stringify(value)}</output></p>
Related marks
treeCheckable enables multiple and parent-child relationships. By default, SHOW_CHILD returns leaf nodes.
<script lang="ts">
import { TreeSelect, type TreeSelectNode, type TreeSelectValue } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
let value = $state<TreeSelectValue>([]);
</script>
<TreeSelect
aria-label={("Related sections")}
{treeData}
{value}
treeCheckable
treeDefaultExpandAll
onChange={next => { value = next; }}
/>
<p><output
aria-label={("Linked selected nodes")}
>{JSON.stringify(value)}</output></p>
treeCheckable content
Text, an empty array and a snippet enable standard checkboxes. Their content is not rendered; multiple retains the selected-value array.
<script lang="ts">
import {
RadioGroup,
TreeSelect,
type TreeSelectCheckableContent,
type TreeSelectValue
} from '@woodger/antd';
const flags: Record<string, TreeSelectCheckableContent> = {
true: true,
false: false,
'"checkbox"': 'checkbox',
'[]': []
};
const treeData = [{ value: 'ui', title: 'UI', children: [
{ value: 'button', title: 'Button' },
{ value: 'input', title: 'Input' }
] }];
let flag = $state('true');
let value = $state<TreeSelectValue>([]);
</script>
<style>
.controls { margin-bottom: 16px; }
</style>
{#snippet checkboxContent()}<strong data-checkable-content>Checkbox</strong>{/snippet}
<div class="controls">
<RadioGroup
aria-label={("treeCheckable value")}
options={['true', 'false', '"checkbox"', '[]', 'Snippet']}
bind:value={flag}
/>
</div>
<TreeSelect
aria-label={("Selection with a treeCheckable flag")}
{treeData}
treeCheckable={flag === 'Snippet' ? checkboxContent : flags[flag]}
{value}
multiple
showSearch={false}
treeDefaultExpandAll
onChange={next => { value = next; }}
/>
<p><output aria-label={("Selected nodes with a treeCheckable flag")}>
{JSON.stringify(value)}
</output></p>
Changing the limit preserves selection; changing the mode clears it in this example. SHOW_PARENT and non-strict SHOW_ALL disable a nonzero limit; maxCount=0 prevents new selections.
TreeSelect selection limit
maxCount limits multiple and checkbox selection. Compare strategies and strict mode; initial values exceeding the limit are preserved.
<script lang="ts">
import { TreeSelect, type TreeSelectValue } from '@woodger/antd';
const modes = ['multiple', 'SHOW_CHILD', 'SHOW_PARENT', 'SHOW_ALL', 'strict'] as const;
let mode = $state<typeof modes[number]>('multiple');
let maxCount = $state(2);
let value = $state<TreeSelectValue>(['button']);
const strategy = $derived(
mode === 'SHOW_CHILD' || mode === 'SHOW_PARENT' || mode === 'SHOW_ALL'
? mode
: undefined
);
const treeData = $derived([
{ value: 'ui', title: ("Interface"), children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: ("Data"), children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] }
]);
</script>
<div class="controls">
<label>maxCount <select value={maxCount} onchange={event => {
maxCount = Number(event.currentTarget.value);
}}>
{#each [0, 1, 2, 3] as count (count)}<option value={count}>{count}</option>{/each}
</select></label>
<label>{("Limit mode")} <select value={mode} onchange={event => {
const next = modes.find(item => item === event.currentTarget.value);
if (next) {
mode = next;
value = [];
}
}}>
{#each modes as item (item)}<option
value={item}
>{item === 'strict' ? 'treeCheckStrictly' : item}</option>{/each}
</select></label>
</div>
<TreeSelect aria-label={("Limited TreeSelect selection")}
{treeData} {value} {maxCount} multiple treeDefaultExpandAll allowClear
treeCheckable={mode !== 'multiple'} treeCheckStrictly={mode === 'strict'}
showCheckedStrategy={strategy} showSearch={{ treeNodeFilterProp: 'title' }}
onChange={next => { value = next; }} />
<p><output
aria-label={("Limited TreeSelect value")}
>{JSON.stringify(value)}</output></p>
<p>
{("Changing the limit preserves selection; changing the mode clears it in this example. SHOW_PARENT and non-strict SHOW_ALL disable a nonzero limit; maxCount=0 prevents new selections.")}
</p>
<style>
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-block-end: 12px;
}
</style>
SHOW_ALL
SHOW_PARENT
SHOW_CHILD
Strategies for marked nodes
SHOW_ALL shows the parent and children, SHOW_PARENT collapses the branch, SHOW_CHILD leaves the leaves.
<script lang="ts">
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
const strategies = ['SHOW_ALL', 'SHOW_PARENT', 'SHOW_CHILD'] as const;
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
p {
margin: 0 0 8px;
}
</style>
<div class="examples">
{#each strategies as strategy (strategy)}
<div><p>{(strategy)}</p><TreeSelect
aria-label={("TreeSelect Strategy " + String((strategy)) + "")}
{treeData}
treeCheckable
showCheckedStrategy={strategy}
defaultValue={['button', 'input']}
treeDefaultExpandAll
/></div>
{/each}
</div>
Independent marks
treeCheckStrictly disables parent-child relationships and enables labelInValue. The result is objects with value and label.
<script lang="ts">
import { TreeSelect, type TreeSelectNode, type TreeSelectValue } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
let value = $state<TreeSelectValue>([]);
</script>
<TreeSelect
aria-label={("Independent sections")}
{treeData}
{value}
treeCheckStrictly
treeDefaultExpandAll
onChange={next => { value = next; }}
/>
<p><output
aria-label={("Independent selected nodes")}
>{JSON.stringify(value)}</output></p>
Value with label
labelInValue returns an object instead of a simple key. A numeric key retains the type number.
<script lang="ts">
import { TreeSelect, type TreeSelectValue } from '@woodger/antd';
let value = $state<TreeSelectValue>(null);
</script>
<TreeSelect aria-label={("Section with label")} treeData={[{
value: 10,
title: "Documentation"
}, { value: 20, title: "Examples" }]}
{value} labelInValue allowClear onChange={next => { value = next ?? null; }} />
<p><output aria-label={("Selected node object")}>{JSON.stringify(value)}</output></p>
Search by label
showSearch sets controlled searchValue and filtering by title. Nested matches preserve the parent branch.
<script lang="ts">
import { TreeSelect, type TreeSelectNode, type TreeSelectValue } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
let value = $state<TreeSelectValue>(null);
let search = $state('');
function handleChange(next: TreeSelectValue) {
value = next ?? null;
search = '';
}
</script>
<TreeSelect aria-label={("Search section")} {treeData} {value} treeDefaultExpandAll
showSearch={{
treeNodeFilterProp: 'title',
searchValue: search,
onSearch: next => { search = next; }
}}
notFoundContent={("No sections found")} onChange={handleChange} />
<p><output aria-label={("Search and selected section")}>{(search
|| ("Empty search"))}; {JSON.stringify(value)}</output></p>
Search:
Selected:
Search separators
tokenSeparators accepts an array or a function. A separator clears the query and closes the popup while retaining selection; it does not automatically select nodes.
<script lang="ts">
import {
Button,
TreeSelect,
type TreeSelectTokenSeparators,
type TreeSelectValue
} from '@woodger/antd';
const treeData = [{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }];
let value = $state<TreeSelectValue>(['button']);
let search = $state('');
let splitter = $state('array');
const tokenSeparators = $derived<TreeSelectTokenSeparators>(
splitter === 'function'
? text => text.split(/[;\r\n]+/)
: [',', '\n']
);
</script>
<div class="controls">
<label>{("Search separators")} <select bind:value={splitter}>
<option value="array">{("Comma and newline")}</option>
<option value="function">{("Function: semicolon")}</option>
</select></label>
<Button onclick={() => { search = ''; value = ['button']; }}>
{("Reset separator example")}
</Button>
</div>
<TreeSelect
aria-label={("TreeSelect search with separators")}
{treeData}
{value}
multiple
{tokenSeparators}
showSearch={{
searchValue: search,
treeNodeFilterProp: 'title',
onSearch: next => { search = next; }
}}
onChange={next => { value = next ?? []; search = ''; }}
/>
<p>{("Search: ")}<output aria-label={("Search with separators")}>{search
|| ("Empty search")}</output></p>
<p>{("Selected: ")}<output
aria-label={("Selected nodes with separators")}
>{JSON.stringify(value)}</output></p>
<style>
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
select { max-width: 100%; }
label { min-width: 0; }
</style>
Asynchronous download
loadData returns a Promise and updates treeData. The search does not bring up the bootloader. The timer and pending Promise terminate when unmounted.
<script lang="ts">
import { onDestroy } from 'svelte';
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
let treeData = $state<TreeSelectNode[]>([{ value: 'catalog', title: "Catalog", isLeaf: false }]);
let pending = $state(false);
let timer: ReturnType<typeof setTimeout> | undefined;
let finish: (() => void) | undefined;
function handleLoad() {
pending = true;
return new Promise<void>(resolve => {
finish = resolve;
timer = setTimeout(() => {
treeData = [{ value: 'catalog', title: "Catalog", isLeaf: false, children: [
{ value: 'guides', title: "Manuals", isLeaf: true }
] }];
pending = false;
timer = undefined;
finish = undefined;
resolve();
}, 600);
});
}
onDestroy(() => {
clearTimeout(timer);
finish?.();
});
</script>
<TreeSelect
aria-label={("Loading section")}
{treeData}
loadData={handleLoad}
placeholder={("Expand catalog")}
/>
<p><output aria-label={("Tree loading status")}>{(pending ? "Loading…" : "Catalog ready")}</output></p>
Ctrl, Meta and Shift preserve selection without expanding by title. The switcher button and keyboard work independently.
TreeSelect title expansion
treeExpandAction: false, click or doubleClick. Selection and expansion are controlled independently; changing the mode preserves state.
<script lang="ts">
import {
TreeSelect,
type TreeExpandAction,
type TreeKey,
type TreeSelectValue
} from '@woodger/antd';
let action = $state<TreeExpandAction>(false);
let expanded = $state<TreeKey[]>([]);
let value = $state<TreeSelectValue>([]);
const treeData = $derived([
{
value: 'ui', title: ("Interface"), children: [
{ value: 'button', title: 'Button', isLeaf: true },
{ value: 'input', title: 'Input', isLeaf: true }
]
}
]);
</script>
<style>
label {
display: block;
margin-block-end: 12px;
}
</style>
<label>treeExpandAction <select value={String(action)} onchange={event => {
const next = event.currentTarget.value;
action = next === 'click' || next === 'doubleClick' ? next : false;
}}>
<option value="false">false</option>
<option value="click">click</option>
<option value="doubleClick">doubleClick</option>
</select></label>
<TreeSelect aria-label={("TreeSelect title expansion")}
{treeData} {value} multiple showSearch={false} treeExpandAction={action}
treeExpandedKeys={expanded} onTreeExpand={keys => { expanded = keys; }}
onChange={next => { value = next; }} />
<p><output aria-label="treeExpandedKeys">{JSON.stringify(expanded)}</output></p>
<p><output aria-label="value">{JSON.stringify(value)}</output></p>
<p>
{("Ctrl, Meta and Shift preserve selection without expanding by title. The switcher button and keyboard work independently.")}
</p>
Tree lines and switch
treeLine shows connections, showLeafIcon controls leaves. switcherIcon gets TreeEventNode; treeIcon includes node icons.
<script lang="ts">
import { TreeSelect, type TreeEventNode, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
</script>
{#snippet switcher(node: TreeEventNode)}<span aria-hidden="true">{(node.expanded ? '−' : '+')}</span>{/snippet}
<TreeSelect
aria-label={("Tree with lines")}
{treeData}
treeDefaultExpandAll
treeLine={{ showLeafIcon: true }}
treeIcon
switcherIcon={switcher}
/>
Tree position
Four placement values specify the preferred placement of the popup. classNames.popup.root adds the panel frame class.
<script lang="ts">
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
const placements = ['topLeft', 'topRight', 'bottomLeft', 'bottomRight'] as const;
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
:global(.tree-select-example-popup) {
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
}
</style>
<div class="examples">
{#each placements as placement (placement)}
<TreeSelect
aria-label={("Tree position " + String((placement)) + "")}
{treeData}
{placement}
classNames={{ popup: { root: 'tree-select-example-popup' } }}
placeholder={(placement)}
/>
{/each}
</div>
popupAlign.offset: [16, 12]
builtinPlacements: 16 px popup gap
TreeSelect popup alignment
PopupAlign changes the offset; builtinPlacements replaces the placement map. Compare the gaps for the two controls.
<script lang="ts">
import { TreeSelect, type TreeSelectPopupAlign } from '@woodger/antd';
const treeData = [{ value: 'ui', title: 'UI', children: [
{ value: 'button', title: 'Button' },
{ value: 'input', title: 'Input' }
] }];
const overflow = { adjustX: true, adjustY: true };
const placements = {
bottomLeft: { points: ['tl', 'bl'], offset: [0, 16], overflow },
bottomRight: { points: ['tr', 'br'], offset: [0, 16], overflow },
topLeft: { points: ['bl', 'tl'], offset: [0, -16], overflow },
topRight: { points: ['br', 'tr'], offset: [0, -16], overflow }
} satisfies Readonly<Record<string, TreeSelectPopupAlign>>;
</script>
<style>
.examples {
display: grid;
gap: 20px;
}
p { margin: 0 0 8px; }
</style>
<div class="examples">
<div>
<p><code>popupAlign.offset: [16, 12]</code></p>
<TreeSelect
aria-label={("TreeSelect popup offset")}
{treeData}
placement="bottomLeft"
popupAlign={{ offset: [16, 12] }}
placeholder={("Choose a component")}
treeDefaultExpandAll
/>
</div>
<div>
<p><code>builtinPlacements</code>: {("16 px popup gap")}</p>
<TreeSelect
aria-label={("Custom TreeSelect placements")}
{treeData}
placement="bottomLeft"
builtinPlacements={placements}
placeholder={("Choose a component")}
treeDefaultExpandAll
/>
</div>
</div>
TreeSelect popup animation
The default transition, a custom CSS name and animation. An empty transitionName disables named motion; animation takes precedence.
<script lang="ts">
import { RadioGroup, TreeSelect, type TreeSelectValue } from '@woodger/antd';
const treeData = [{ value: 'ui', title: 'UI', children: [
{ value: 'button', title: 'Button' },
{ value: 'input', title: 'Input' }
] }];
let mode = $state('default');
let value = $state<TreeSelectValue>(['button']);
let search = $state('');
const animation = $derived(mode === 'animation' ? 'fade' : undefined);
const transitionName = $derived.by(() => {
if (mode === 'default') {
return undefined;
}
if (mode === 'transition') {
return 'tree-select-example-fade';
}
return '';
});
</script>
<style>
.controls { margin-bottom: 16px; }
:global(.tree-select-example-fade-appear),
:global(.tree-select-example-fade-enter),
:global(.tree-select-example-motion-dropdown-fade-appear),
:global(.tree-select-example-motion-dropdown-fade-enter) {
opacity: 0;
}
:global(.tree-select-example-fade-appear-active),
:global(.tree-select-example-fade-enter-active),
:global(.tree-select-example-motion-dropdown-fade-appear-active),
:global(.tree-select-example-motion-dropdown-fade-enter-active) {
animation: tree-select-example-show var(--ant-motion-duration-mid, .2s) ease both;
}
:global(.tree-select-example-fade-leave-active),
:global(.tree-select-example-motion-dropdown-fade-leave-active) {
animation: tree-select-example-hide var(--ant-motion-duration-mid, .2s) ease both;
}
@keyframes tree-select-example-show {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes tree-select-example-hide {
from { opacity: 1; }
to { opacity: 0; }
}
</style>
<div class="controls">
<RadioGroup
aria-label={("TreeSelect popup transition")}
options={([
{ value: 'default', label: "Default transition" },
{ value: 'transition', label: 'transitionName' },
{ value: 'animation', label: 'animation' },
{ value: 'none', label: "No animation" }
])}
bind:value={mode}
/>
</div>
<TreeSelect
aria-label={("TreeSelect with popup animation")}
prefixCls="tree-select-example-motion"
{treeData}
{value}
{animation}
{transitionName}
multiple
treeDefaultExpandAll
classNames={{ popup: { root: 'tree-select-example-motion-popup' } }}
showSearch={{
searchValue: search,
treeNodeFilterProp: 'title',
onSearch: next => { search = next; }
}}
onChange={next => { value = next; }}
/>
Design options
outlined, filled, borderless and underlined use the same tree and node selection.
<script lang="ts">
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
const variants = ['outlined', 'filled', 'borderless', 'underlined'] as const;
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
</style>
<div class="examples">
{#each variants as variant (variant)}<TreeSelect aria-label={("TreeSelect option " + String((variant)) + "")} {treeData} {variant} placeholder={(variant)} />{/each}
</div>
Test states
error and warning specify the status. A completely inaccessible field and an inaccessible node are shown separately.
<script lang="ts">
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
</style>
<div class="examples">
<TreeSelect
aria-label={("Section with error")}
{treeData}
status="error"
placeholder={("Error")}
/>
<TreeSelect
aria-label={("Sections with warning")}
{treeData}
multiple
status="warning"
placeholder={("Warning")}
/>
<TreeSelect
aria-label={("Inaccessible tree")}
{treeData}
disabled
defaultValue="button"
/>
</div>
Dimensions
large, medium and small. A field without a local size inherits the section settings.
<script lang="ts">
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
const sizes = ['large', 'medium', 'small'] as const;
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
</style>
<div class="examples">
{#each sizes as size (size)}<TreeSelect aria-label={("Size TreeSelect " + String((size)) + "")} {treeData} {size} placeholder={(size)} />{/each}
</div>
Own node label
treeTitleRender - Svelte snippet. It changes the label in the tree and the selected value, preserving the key.
<script lang="ts">
import type { Snippet } from 'svelte';
import { Button, Flex, TreeSelect, type TreeSelectNode } from '@woodger/antd';
let mounted = $state(true);
let savedLabel = $state<Snippet>();
const treeData: TreeSelectNode[] = [
{ value: 'ui', title: "Interface", selectable: false, children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] },
{ value: 'data', title: "Data", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Inaccessible section", disabled: true }
];
</script>
{#snippet title(node: TreeSelectNode)}
<span>
{#if typeof node.title === 'function'}
{@render node.title()}
{:else}
{(node.title)}
{/if}
{#if node.children}
<small>({(node.children.length)})</small>
{/if}
</span>
{/snippet}
<Flex vertical align="start" gap="medium">
{#if mounted}
<TreeSelect
aria-label={("Tree with its labels")}
{treeData}
treeDefaultExpandAll
treeTitleRender={title}
defaultValue="button"
onChange={(_value, labels) => {
const label = labels?.[0];
savedLabel = typeof label === 'function' ? label : undefined;
}}
/>
{/if}
<Button
onclick={() => { mounted = !mounted; }}
>{("Show or hide TreeSelect")}</Button>
</Flex>
<output
aria-label={("Saved TreeSelect label")}
>{#if savedLabel}{@render savedLabel()}{/if}</output>
<style>
output {
display: block;
margin-top: 12px;
}
</style>
fieldNames
treeDataSimpleMode
Custom schema and flat data
fieldNames maps record fields; treeDataSimpleMode builds an id/pId hierarchy. The callback receives the original fields.
<script lang="ts">
import { TreeSelect } from '@woodger/antd';
interface Entry { code: string; caption: string; payload: { section: string }; nodes?: Entry[] }
const records: Entry[] = [{ code: 'ui', caption: 'UI', payload: { section: 'ui' }, nodes: [
{ code: 'button', caption: 'Button', payload: { section: 'ui' } }
] }];
const flat = [
{ id: 1, pId: 0, value: 'ui', title: 'UI' },
{ id: 2, pId: 1, value: 'button', title: 'Button' }
];
let selected = $state('');
</script>
<div class="examples">
<div>
<p>fieldNames</p>
<TreeSelect aria-label={("Custom TreeSelect fields")} treeData={records}
fieldNames={{ value: 'code', label: 'caption', children: 'nodes' }} treeDefaultExpandAll
showSearch={{ treeNodeFilterProp: 'caption' }}
onSelect={(
_value,
node
) => { selected = node ? `${node.code}: ${node.payload.section}` : ''; }} />
<output aria-label={("Original TreeSelect record")}>{selected}</output>
</div>
<div>
<p>treeDataSimpleMode</p>
<TreeSelect aria-label={("Flat TreeSelect data")} treeData={flat}
treeDataSimpleMode={{ rootPId: 0 }} treeDefaultExpandAll />
</div>
</div>
<style>.examples {
display: grid;
gap: 16px;
} p {
margin: 0 0 8px;
} output {
display: block;
margin-top: 8px;
}</style>
TreeSelect control and popup slots
prefix, suffix, a clear icon and popupRender. The popup field retains its draft when reopened.
<script lang="ts">
import type { Snippet } from 'svelte';
import { TreeSelect, Input, type TreeSelectSuffixInfo } from '@woodger/antd';
let draft = $state('');
const treeData = [{ value: 'ui', title: 'UI', children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] }];
</script>
{#snippet popup(menu: Snippet)}
{@render menu()}
<div class="popup-footer">
<Input aria-label={("Draft inside the TreeSelect popup")} bind:value={draft} />
</div>
{/snippet}
{#snippet suffix(info: TreeSelectSuffixInfo)}<span
aria-hidden="true"
>{info.open ? '▴' : '▾'}</span>{/snippet}
<TreeSelect aria-label={("Custom TreeSelect popup")} {treeData} treeDefaultExpandAll
prefix="UI" {suffix} popupRender={popup}
allowClear={{ clearIcon: '×', label: ("Clear TreeSelect") }}
showSearch={{ treeNodeFilterProp: 'title' }} />
<style>
.popup-footer {
padding: 8px;
border-top: 1px solid var(--ant-color-border-secondary);
}
</style>
Semantic styles TreeSelect
ConfigProvider defaults, a styles function, placeholder and switcher snippets. A local slot overrides provider styles.
<script lang="ts">
import { ConfigProvider, TreeSelect } from '@woodger/antd';
let outlined = $state(true);
const treeData = [{ value: 'ui', title: 'UI', children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
] }];
</script>
<label><input
type="checkbox"
bind:checked={outlined}
/>{("Highlight the TreeSelect popup")}</label>
{#snippet placeholder()}<em>{("Choose a component")}</em>{/snippet}
{#snippet switcher(node: { expanded: boolean })}<span
aria-hidden="true"
>{node.expanded ? '−' : '+'}</span>{/snippet}
<ConfigProvider treeSelect={{
variant: 'filled', switcherIcon: switcher,
styles: { popup: { root: 'border:1px solid var(--ant-color-primary-border)' } }
}}>
<TreeSelect
aria-label={("TreeSelect styling")}
{treeData}
{placeholder}
treeDefaultExpandAll
classNames={{ popup: { root: 'tree-select-semantic-popup' } }}
styles={({ props }) => ({
root: props.variant === 'filled' ? 'border-radius:8px' : undefined,
popup: {
root: outlined
? `
outline: 2px solid var(--ant-color-primary);
outline-offset: 2px;
`
: 'outline:none'
}
})}
/>
</ConfigProvider>
<style>
label {
display: block;
margin-bottom: 16px;
}
</style>
Large TreeSelect tree
600 nodes, ConfigProvider.virtual, row height estimates and scrolling to a key through TreeSelectRef.
<script lang="ts">
import { tick } from 'svelte';
import {
Button,
ConfigProvider,
TreeSelect,
type TreeSelectRef,
type TreeScrollConfig
} from '@woodger/antd';
const treeData = Array.from({ length: 600 }, (_, index) => ({
value: index,
title: `Node ${index}`
}));
let control = $state<TreeSelectRef>();
let opened = $state(false);
let virtual = $state(true);
async function scrollTo(config: TreeScrollConfig) {
opened = true;
await tick();
control?.scrollTo(config);
control?.focus();
}
</script>
<div class="controls">
<label><input type="checkbox" bind:checked={virtual} />ConfigProvider.virtual</label>
<Button onclick={() => { opened = true; }} >{("Open the large tree")}</Button>
<Button onclick={() => scrollTo({ key: 480, align: 'top' })}>scrollTo 480</Button>
<Button onclick={() => scrollTo({ top: 0 })}>{("Back to the start")}</Button>
</div>
<ConfigProvider {virtual} popupMatchSelectWidth={true}>
<TreeSelect bind:this={control} aria-label={("Virtual TreeSelect")}
{treeData} open={opened} onOpenChange={next => { opened = next; }}
listHeight={224} listItemHeight={28} listItemScrollOffset={4}
showSearch={{ treeNodeFilterProp: 'title' }} />
</ConfigProvider>
<style>.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}</style>
Declarative TreeSelect nodes
TreeSelect.TreeNode and named TreeSelectTreeNode, a static strategy, icons and row styling.
<script lang="ts">
import { TreeSelect, TreeSelectTreeNode, type TreeEventNode } from '@woodger/antd';
</script>
{#snippet icon(node: TreeEventNode)}<span
aria-hidden="true"
>{node.isLeaf ? '•' : '▣'}</span>{/snippet}
{#snippet switcher(node: TreeEventNode)}<span
aria-hidden="true"
>{node.expanded ? '−' : '+'}</span>{/snippet}
<TreeSelect
aria-label={("Declarative TreeSelect nodes")}
treeCheckable
treeDefaultExpandAll
showCheckedStrategy={TreeSelect.SHOW_PARENT}
treeIcon
switcherIcon={switcher}
>
<TreeSelect.TreeNode value="ui" title="UI" {icon}>
<TreeSelect.TreeNode value="button" title="Button" {icon} isLeaf
class="tree-select-featured-node" style="font-weight:600" data-component="button" />
<TreeSelectTreeNode value="input" title="Input" {icon} isLeaf />
</TreeSelect.TreeNode>
</TreeSelect>
TreeSelect focus and events
showAction opens the tree on focus. The log shows native, input and root callback order and Enter cancellation.
<script lang="ts">
import { Button, TreeSelect, type TreeSelectRef, type TreeSelectValue } from '@woodger/antd';
const treeData = [{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }];
let control = $state<TreeSelectRef>();
let focusAction = $state(true);
let mode = $state('multiple');
let searchable = $state(false);
let cancellation = $state('none');
let value = $state<TreeSelectValue>([]);
let events = $state<string[]>([]);
function record(kind: string, event?: Event) {
const target = event?.currentTarget instanceof Element
? event.currentTarget.tagName
: '';
const key = event instanceof KeyboardEvent ? event.key : '';
events = [...events, [kind, key, target].filter(Boolean).join(' ')].slice(-12);
}
</script>
<div class="controls">
<label>{("Event control mode")} <select value={mode} onchange={event => {
mode = event.currentTarget.value;
value = mode === 'multiple' ? [] : null;
}}>
<option value="single">single</option>
<option value="multiple">multiple</option>
</select></label>
<label><input
type="checkbox"
bind:checked={searchable}
/>{("Search in event control")}</label>
<label><input type="checkbox" bind:checked={focusAction} />showAction=['focus']</label>
<label>{("Enter cancellation")} <select bind:value={cancellation}>
<option value="none">{("No cancellation")}</option>
<option value="native">onkeydown.preventDefault()</option>
<option value="hook">onInputKeyDown.preventDefault()</option>
</select></label>
<Button onclick={() => control?.focus()}>{("Focus the TreeSelect event example")}</Button>
<Button onclick={() => { events = []; }}>{("Clear event log")}</Button>
</div>
<TreeSelect
bind:this={control}
aria-label={("TreeSelect events")}
{treeData}
{value}
multiple={mode === 'multiple'}
showSearch={searchable}
allowClear
tabIndex={0}
showAction={focusAction ? ['focus'] : []}
onOpenChange={open => record(`open=${open}`)}
onChange={next => { value = next ?? (mode === 'multiple' ? [] : null); record('change'); }}
onkeydown={event => {
record('native', event);
if (cancellation === 'native' && event.key === 'Enter') event.preventDefault();
}}
onInputKeyDown={event => {
record('input', event);
if (cancellation === 'hook' && event.key === 'Enter') event.preventDefault();
}}
onKeyDown={event => record('root', event)}
onKeyUp={event => record('keyup', event)}
onFocus={event => record('focus', event)}
onBlur={event => record('blur', event)}
onMouseDown={event => record('mousedown', event)}
onClick={event => record('click', event)}
onMouseEnter={event => record('mouseenter', event)}
onMouseLeave={event => record('mouseleave', event)}
/>
<p><output
aria-label={("Selection in the event example")}
>{JSON.stringify(value)}</output></p>
<pre aria-label={("TreeSelect event log")}>{events.join('\n')}</pre>
<style>
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
label { min-width: 0; }
select { max-width: 100%; }
pre {
min-height: 4em;
max-height: 12em;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: 12px;
}
</style>
Selected:
nativeElement:
Custom TreeSelect root
components.root replaces the entire control. Button receives attributes and registers its DOM; the owner supplies its label and ARIA.
RootTreeSelect.svelte<script lang="ts"> import { Button, Checkbox, TreeSelect, type TreeSelectRef, type TreeSelectRootContext, type TreeSelectValue } from '@woodger/antd'; import ComponentButton from './ComponentButton.svelte'; const treeData = [{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }]; let value = $state<TreeSelectValue>(null); let open = $state(false); let custom = $state(true); let control = $state<TreeSelectRef>(); let nativeElement = $state<HTMLButtonElement | HTMLDivElement>(); const label = $derived.by(() => { const selectedNode = treeData.find(node => node.value === value); const title = selectedNode?.title; return title ?? ("Choose a component"); }); </script> {#snippet root(context: TreeSelectRootContext<HTMLButtonElement>)} <ComponentButton {context} {label} /> {/snippet} <div class="controls"> <Checkbox bind:checked={custom}>{("Custom TreeSelect root")}</Checkbox> <Button onclick={() => control?.focus()}>{("Focus TreeSelect root")}</Button> <Button onclick={() => { value = null; open = false; }} >{("Reset root")}</Button> </div> <TreeSelect id="tree-select-components-root" aria-label={("Selection through a custom root")} {treeData} {value} {open} bind:this={control} bind:nativeElement onOpenChange={next => { open = next; }} onChange={next => { value = next ?? null; }} components={custom ? { root: { render: root, props: { id: 'tree-select-components-root', 'aria-haspopup': 'tree', 'aria-expanded': open, 'aria-controls': open ? 'tree-select-components-root-list' : undefined } } } : undefined} /> <p>{("Selected: ")}<output aria-label={("Custom root selection")}>{JSON .stringify(value)}</output></p> <p>nativeElement: <output aria-label={("Custom root DOM")}>{nativeElement ?.tagName ?? '—'}</output></p> <style> .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-bottom: 16px; } </style>ComponentButton.svelte<script lang="ts"> import { Button, type ButtonProps, type TreeSelectRootContext } from '@woodger/antd'; let { context, label }: { context: TreeSelectRootContext<HTMLButtonElement>; label: string } = $props(); let element = $state<HTMLButtonElement | HTMLAnchorElement>(); const register = $derived(context.register); const buttonProps = $derived.by<ButtonProps>(() => { const { type, color: _nativeColor, class: className, ...attributes } = context.attributes; return { ...attributes, class: className == null ? undefined : String(className), htmlType: type ?? 'button' }; }); $effect(() => { if (element instanceof HTMLButtonElement) { return register(element); } }); </script> <Button {...buttonProps} block bind:nativeElement={element}>{label}</Button>
Selected:
inputElement:
Custom TreeSelect editor
components.input replaces only the editor. Textarea retains tags and responsive layout; the log shows props, native, hook and root callbacks.
<script lang="ts">
import {
Checkbox,
TreeSelect,
type TreeSelectInputContext,
type TreeSelectValue
} from '@woodger/antd';
const treeData = [{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }, {
value: 'table',
title: 'Table'
}];
let value = $state<TreeSelectValue>(['button', 'input']);
let search = $state('');
let custom = $state(true);
let inputElement = $state<HTMLInputElement | HTMLTextAreaElement>();
let events = $state<string[]>([]);
function record(kind: string, event: KeyboardEvent) {
const tag = event.currentTarget instanceof Element
? event.currentTarget.tagName
: '';
events = [...events, `${kind} ${event.key} ${tag}`].slice(-8);
}
</script>
{#snippet editor({ attributes, register }: TreeSelectInputContext<HTMLTextAreaElement>)}
<textarea {...attributes} rows={1} {@attach register}></textarea>
{/snippet}
<div class="controls">
<Checkbox bind:checked={custom}>
{("Textarea editor in TreeSelect")}
</Checkbox>
</div>
<TreeSelect
aria-label={("Selection with a custom editor")}
{treeData}
{value}
multiple
maxTagCount="responsive"
bind:inputElement
onChange={next => { value = next ?? []; search = ''; }}
showSearch={{
searchValue: search,
treeNodeFilterProp: 'title',
onSearch: next => { search = next; }
}}
components={custom ? {
input: {
render: editor, props: {
onkeydown: event => record(
'props',
event
)
}
}
} : undefined}
onkeydown={event => record('native', event)}
onInputKeyDown={event => record('hook', event)}
onKeyDown={event => record('root', event)}
/>
<p>{("Selected: ")}<output
aria-label={("Custom editor selection")}
>{JSON.stringify(value)}</output></p>
<p>inputElement: <output aria-label={("Custom editor DOM")}>{inputElement
?.tagName
?? '—'}</output></p>
<pre aria-label={("Editor handler order")}>{events.join('\n')}</pre>
<style>
.controls { margin-bottom: 16px; }
textarea { resize: none; }
pre {
max-height: 8em;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: 12px;
}
</style>
Custom editor in Form
Input registers a composite ref with focus/blur. Form stores the selected node, validates the field and remounts the editor on reset.
ComponentsFormTreeSelect.svelte<script lang="ts"> import { Button, Form, FormItem, TreeSelect, createForm, type TreeSelectInputContext, type TreeSelectValue } from '@woodger/antd'; import ComponentInput from './ComponentInput.svelte'; const form = createForm<{ component: TreeSelectValue }>({ initialValues: { component: null } }); const treeData = [{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }]; let result = $state('—'); </script> {#snippet editor(context: TreeSelectInputContext<HTMLInputElement>)}<ComponentInput {context} />{/snippet} <Form {form} aria-label={("Form with a custom TreeSelect editor")} onFinish={values => { result = JSON.stringify(values.component); }} > <FormItem name="component" label={("Component with a custom editor")} rules={([{ required: true, message: "Select a component in the custom editor field." }])} > <TreeSelect {treeData} value={form.values.component} components={{ input: editor }} showSearch={{ treeNodeFilterProp: 'title' }} onChange={next => form.setFieldValue( 'component', next ?? null )} /> </FormItem> <div class="actions"> <Button htmlType="submit" type="primary">{("Save component")}</Button> <Button onclick={() => form.focusField('component')}> {("Focus editor through Form")} </Button> <Button htmlType="reset" onclick={() => { result = '—'; }} >{("Reset component")}</Button> </div> </Form> <p><output aria-label={("Form editor result")}>{result}</output></p> <style> .actions { display: flex; flex-wrap: wrap; gap: 12px; } </style>ComponentInput.svelte<script lang="ts"> import { Input, type TreeSelectInputContext } from '@woodger/antd'; let { context }: { context: TreeSelectInputContext<HTMLInputElement> } = $props(); let input = $state<HTMLInputElement>(); let nativeElement = $state<HTMLElement>(); let control = $state<{ focus(options?: FocusOptions): void; blur(): void }>(); const register = $derived(context.register); const inputProps = $derived.by(() => { const { value, defaultValue, size, class: className, ...attributes } = context.attributes; return { ...attributes, value: String(value ?? ''), defaultValue: defaultValue === undefined ? undefined : String(defaultValue), class: className == null ? undefined : String(className), htmlSize: size ?? undefined }; }); $effect(() => { const editor = input, root = nativeElement, instance = control; if (!editor || !root || !instance) { return; } return register({ inputElement: editor, nativeElement: root, focus: options => instance.focus(options), blur: () => instance.blur() }); }); </script> <Input {...inputProps} bind:inputElement={input} bind:nativeElement bind:this={control} />
Subscription to sections in Form
Original form from the review: associated check-ins, search, required selection, submit and reset. Form stores leaf keys.
<script lang="ts">
import { TreeSelect, Form, FormItem, Button, createForm } from '@woodger/antd';
const data = [
{
value: 'components',
title: "Components",
children: [
{ value: 'button', title: 'Button' },
{ value: 'input', title: 'Input' },
{ value: 'select', title: 'Select' }
]
},
{
value: 'docs',
title: "Documentation",
children: [{ value: 'start', title: "Getting started" }]
}
];
const form = createForm<{ topics: string[] }>(
{
initialValues: { topics: ['button'] },
rules: ({ topics: [{ required: true, message: "Select sections." }] })
}
);
let result = $state('');
</script>
<style>
output {
display: block;
margin-top: 16px;
}
</style>
<div style="
max-width: 640px;
min-width: 0;
">
<Form {form} onFinish={values => { result = values.topics.join(', '); }}>
<FormItem name="topics" label={("Subscription to sections")}><TreeSelect
treeData={data}
value={form.values.topics}
treeCheckable
treeDefaultExpandAll
showSearch={{ treeNodeFilterProp: 'title' }}
allowClear
placeholder={("Select sections")}
onChange={next => form.setFieldValue('topics', next)}
/></FormItem>
<div
style="
display: flex;
gap: 8px;
flex-wrap: wrap;
"
><Button
type="primary"
htmlType="submit"
>{("Save sections")}</Button><Button
htmlType="reset"
>{("Reset partitions")}</Button></div>
</Form>
<output aria-label={("Saved sections")}>{result}</output>
</div>
Without a local value, control uses the general -select, popup uses the general -tree-select-dropdown. With local prefixCls both use the same namespace and popup adds -dropdown. The nested tree preserves the native Tree adapter and its own classes: the local prefix TreeSelect is not equal to Tree.prefixCls.
CSS prefixes TreeSelect
Common namespace ConfigProvider and local prefixCls; the state of the component is preserved when the name is changed.
<script lang="ts">
import { Checkbox, ConfigProvider, TreeSelect, type TreeSelectValue } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-tree-select' : '');
let value = $state<TreeSelectValue>(['docs']);
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("Common prefix TreeSelect suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Local prefix TreeSelect")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'tree-select-theme' } }}>
<div class="prefix-stage">
<TreeSelect prefixCls={localPrefix} {value} onChange={next => value = next}
treeCheckable treeDefaultExpandAll showSearch={{ treeNodeFilterProp: 'title' }}
aria-label={("TreeSelect with prefix")}
style="width:100%" treeData={[
{
value: 'project', title: "Project", children: [
{ value: 'docs', title: "Documentation" }, { value: 'examples', title: "Examples" }
]
}
]} />
<output
aria-label={("TreeSelect with prefix")}
>{JSON.stringify(value)}</output>
</div>
</ConfigProvider>
<output
aria-label={("TreeSelect CSS prefix")}
>{("General: ")}{prefix}{("; local: ")}{(localPrefix
|| ("from the provider"))}</output>
<p>
{("Without a local value, control uses the general -select, popup uses the general -tree-select-dropdown. With local prefixCls both use the same namespace and popup adds -dropdown. The nested tree preserves the native Tree adapter and its own classes: the local prefix TreeSelect is not equal to Tree.prefixCls.")}
</p>
</div>
API
Core TreeSelect topics and additional public APIs. Basic and Generate from tree data are combined; separate examples demonstrate popup alignment and animation.
| Theme | Example or limitation |
|---|---|
| Basic / Generate from tree data | A treeData hierarchy; declarative nodes are demonstrated separately. |
| Multiple Selection | Independent selection and removal of tags. |
| Checkable | Related checkbox; additional strategies and strict are shown separately. |
| treeCheckable content | The flag enables checkboxes without rendering its content. |
| Asynchronous loading | Promise, tree update and cleanup. |
| Show Tree Line | Lines, leaves and switcher snippet. |
| TreeSelect title expansion | Three treeExpandAction modes and controlled treeExpandedKeys. |
| Placement | Four panel positions. |
| TreeSelect popup alignment | Offset and a custom placement map. |
| TreeSelect popup animation | Default and custom transitions, and disabling animation. |
| Variants | Four field designs. |
| Status | Error, warning and disabled. |
| Max Count | maxCount limits selection; maxTagCount limits visible tags only. |
| Prefix and Suffix | prefix, suffix, suffixIcon, removeIcon and popupRender. |
| Custom semantic dom styling | classNames/styles objects and functions; ConfigProvider.treeSelect defaults. |
| TreeSelect focus and events | Opening on focus, callback order and cancelling keyboard handling. |
| Search separators | Separator array, function, pasted lines and retaining selected values. |
| Custom TreeSelect root | Full control replacement, attributes, DOM registration and restoring the default root. |
| Custom TreeSelect editor | Textarea instead of input, retaining tags and handler order. |
| Custom editor in Form | Input composite ref, field focus, validation and reset. |
| Virtual list | Virtual rows and scrollTo by key. |
| TreeNode | Declarations, icons and row attributes. |
| Tags | Truncation and responsive tag layout. |
| Data schemas | Custom fields and a flat list. |
| Property | Description | Type | Default |
|---|---|---|---|
components | Root replaces the entire selector and takes priority over input. Input replaces the editor, retaining tags and affixes. A snippet receives attributes/register; an object also accepts props. | TreeSelectComponents<RootElement, EditorElement> | undefined |
tokenSeparators | A readonly string array or (text: string) => string[]. Splitting clears search and closes the popup without onChange/onSelect; IME waits for compositionend. | TreeSelectTokenSeparators | undefined |
showScrollBar | Accepted for compatibility, but not forwarded to the tree and does not affect scrolling. | boolean | "optional" | undefined |
showAction | Focus adds opening on focus. An empty array and click retain pointer opening; changing props while already focused does not open the popup. | ('focus' | 'click')[] | undefined |
autoFocus | Input autofocus after mount; native autofocus takes precedence. Hydration preserves focus on another control. | boolean | undefined |
tabIndex | Input keyboard focus order; native tabindex takes precedence. | number | undefined |
maxLength | As in the original, does not limit TreeSelect search. Use native maxlength for a DOM input limit. | number | undefined |
onInputKeyDown | Input hook after native onkeydown. Its preventDefault does not cancel selection; use native onkeydown to cancel it. | DOMAttributes<EditorElement | HTMLInputElement>['onkeydown'] | undefined |
onKeyDown | Root keyboard callback after internal handling. onKeyUp reports key release. | DOMAttributes<RootElement | HTMLDivElement>['onkeydown'] | undefined |
onFocus | Actual focusin; onBlur receives focusout. currentTarget is the DOM root, a DIV by default. | DOMAttributes<RootElement | HTMLDivElement>['onfocusin'] | undefined |
onMouseDown | Root control event; onClick, onMouseEnter and onMouseLeave are also supported. | DOMAttributes<RootElement | HTMLDivElement>['onmousedown'] | undefined |
styles | Semantic slot CSS strings; local popup slots replace matching provider styles. | TreeSelectSemanticValue<TreeSelectStyles> | undefined |
children | TreeSelect.TreeNode or TreeSelectTreeNode; treeData takes precedence over declarations. | Snippet | undefined |
fieldNames | Field names for value, label and children. Set treeNodeFilterProp explicitly to search a custom label field. | TreeSelectFieldNames | value / label / children |
treeDataSimpleMode | Builds children from id/pId; rootPId specifies the root parent. The children field name remains standard. | boolean | TreeSelectSimpleModeConfig | false |
maxTagCount | Number of visible tags. All selected values remain in callbacks and FormData. | number | "responsive" | undefined |
maxTagTextLength | Truncates tag text; tooltip and callbacks retain full labels. | number | undefined |
maxTagPlaceholder | Summary content or a snippet with omitted records and complete labels. | TreeSelectTagPlaceholder | + N ... |
tagRender | label is a snippet; closable/onClose manage removal. The summary has isMaxTag=true and no value/index/onClose. | Snippet<[TreeSelectTagInfo]> | undefined |
popupRender | Custom popup; calling menu() retains the original tree. Embedded fields can receive focus. | Snippet<[Snippet]> | undefined |
prefix | Content before the input. | TreeSelectLabel | undefined |
suffix | Content or a snippet with open, focused, searchValue, showSearch and loading; takes precedence over suffixIcon. | TreeSelectSuffix | undefined |
suffixIcon | Custom icon; null hides the arrow. | TreeSelectLabel | Standard pointer |
removeIcon | Ordinary tag removal icon. tagRender provides its own markup. | TreeSelectLabel | × |
placeholder | Text, number, array or a snippet for an empty control. | TreeSelectLabel | undefined |
virtual | Row virtualization. popupMatchSelectWidth=false disables it. | boolean | ConfigProvider.virtual / true |
listItemHeight | Initial row height estimate; 0 disables virtualization. | number | controlHeightSM + paddingXXS |
listItemScrollOffset | Additional offset when moving to the active node. | number | 0 |
popupMatchSelectWidth | true matches the control width; false fits the content and disables virtualization. A number sets the width in px; the control width remains the minimum. undefined inherits ConfigProvider. | boolean | number | ConfigProvider / true |
treeIcon | Enables node icons from the icon field. A function acts as a flag; node data supplies the content. | TreeSelectNodeIcon | false |
switcherIcon | Content or a snippet with TreeEventNode. A local value overrides the provider; false leaves an empty switcher. | TreeSelectSwitcherIcon | ConfigProvider.treeSelect |
prefixCls | Full local prefix of Select control and TreeSelect popup. Without it, the generic -select and -tree-select are used; with it both get one namespace. Native Tree adapter saves native classes. | string | ConfigProvider.prefixCls + "-select" |
classNames | Control, tag and popup classes; an object or a function receiving info.props. | TreeSelectSemanticValue<TreeSelectClassNames> | undefined |
treeData | Hierarchy with unique value. Supports custom fields, icon, switcherIcon, class/style and row data-* and aria-* attributes. | readonly Data[] | [] |
value | Managed key, signed object, or array. When clearing single, accept undefined as null to preserve managed mode. bind:value is not supported. | TreeSelectValue | undefined |
defaultValue | Initial local value, read once. | TreeSelectValue | undefined |
onChange | New value and extra.triggerValue. treeTitleRender returns label snippets; with labelInValue they are in value and labels is null. | (value, labels, extra) => void | — |
multiple | Independent selection of multiple nodes. treeCheckable and treeCheckStrictly also include multiple. | boolean | false |
treeCheckable | The value is a flag: a truthy value enables standard checkboxes and multiple. Empty arrays and snippets enable checkboxes; their content is not rendered. | TreeSelectCheckableContent | false |
maxCount | multiple selection limit, including checkbox/strict and missing values. Does not trim initial values. Explicit SHOW_PARENT and non-strict SHOW_ALL disable a nonzero limit; 0 prevents new selections. Does not apply to single selection. | number | undefined |
treeCheckStrictly | Independent checkbox and automatic labelInValue. | boolean | false |
showCheckedStrategy | Manages the tags and result of the associated selection. Without treeCheckable, SHOW_ALL is used. | SHOW_ALL | SHOW_PARENT | SHOW_CHILD | SHOW_CHILD with treeCheckable |
labelInValue | Objects { value, label, halfChecked? } instead of simple keys. | boolean | false |
showSearch | The object contains searchValue, onSearch, filterTreeNode, treeNodeFilterProp and autoClearSearchValue. To search by label, specify title. | boolean | TreeSelectSearchConfig | single: false; multiple: true |
loadData | Loads children with treeData updated. Not called during search. | (node) => PromiseLike<unknown> | — |
treeExpandedKeys | Controlled expansion with onTreeExpand; treeDefaultExpandedKeys and treeDefaultExpandAll set the start. | readonly TreeKey[] | Local state |
treeExpandAction | Title expansion. Ctrl/Meta/Shift suppress expansion while preserving selection. In click mode, onTreeExpand precedes onChange/onSelect. | false | "click" | "doubleClick" | false |
treeLoadedKeys | Managed loaded nodes with onTreeLoad. | readonly TreeKey[] | Local state |
treeLine | Tree connections and display of leaves. treeIcon includes node icons. | boolean | { showLeafIcon: TreeSelectSwitcherIcon } | false |
treeTitleRender | Node content and returned labels. A snippet can be saved and rendered after the control unmounts. | Snippet<[Data]> | Node label |
allowClear | Clearing and onClear. An object sets clearIcon and the accessible label; a nonempty search is cleared with onSearch. | boolean | TreeSelectAllowClear | false |
open | Controlled popup with onOpenChange, defaultOpen sets the start. | boolean | Local state |
listHeight | Tree viewport height. onPopupScroll receives the event from this container. | number | 256 |
placement | Preferred popup side. popupMatchSelectWidth sets the width, getPopupContainer sets the container. | topLeft | topRight | bottomLeft | bottomRight | In interface direction |
popupAlign | Overrides fields of the selected placement; offset, targetOffset and overflow are replaced as whole values. Coordinates are retained until an alignment trigger. | TreeSelectPopupAlign | undefined |
builtinPlacements | Replaces the entire placement map. An empty object does not restore defaults; a missing placement centers the popup. | Readonly<Record<string, TreeSelectPopupAlign>> | undefined |
animation | A nonempty value selects a transition from the Select prefix and animation suffix, overriding transitionName. A custom name requires CSS. | string | undefined |
transitionName | The popup CSS transition name. undefined selects the default slide-up; an empty string disables named motion. | string | ConfigProvider.prefixCls + "-slide-up" |
onOpenChange | Reports a request to open or close the popup. In controlled mode, update open with this value. | (open: boolean) => void | undefined |
onPopupVisibleChange | Accepted without being invoked. Use onOpenChange for popup state changes. | (open: boolean) => void | undefined |
popupStyle | Accepted without being applied. Set popup styling through styles.popup.root. | string | undefined |
choiceTransitionName | Accepted, but the current Overflow does not apply tag animations. | string | undefined |
direction | Accepted without changing direction. ConfigProvider controls RTL and the default placement; HTML dir is a separate attribute. | ltr | rtl | ConfigProvider.direction |
size | Field size; status — error or warning. | large | medium | small | From ConfigProvider |
variant | Local prop → closest Form.variant → ConfigProvider.treeSelect.variant → shared ConfigProvider.variant → outlined. | Variant | From context / outlined |
nativeElement | Ref of the registered root. Without components.root it returns a div; cleared on unmount. | RootElement | HTMLDivElement | — |
inputElement | Editor ref: input or textarea. There is no editor with components.root; removing the input slot restores the default input. | EditorElement | HTMLInputElement | — |
Full types are included in the package. ConfigProvider.treeSelect sets variant, classNames, styles and switcherIcon. Local classes merge with provider classes; local popup slot CSS strings replace the matching provider styles.
Methods
bind:this exposes TreeSelectRef with focus(options?), blur() and scrollTo(config). bind:inputElement and bind:nativeElement expose the DOM elements.
<script lang="ts">
import { Button, TreeSelect, type TreeSelectRef } from '@woodger/antd';
let control = $state<TreeSelectRef>();
</script>
<style>
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
</style>
<div class="controls">
<TreeSelect
bind:this={control}
aria-label={("TreeSelect Methods")}
style="width:min(100%,240px)"
treeData={[{ value: 'docs', title: "Documentation" }]}
/>
<Button onclick={() => control?.focus()}>{("Focus TreeSelect")}</Button>
<Button onclick={() => control?.blur()}>{("Remove focus TreeSelect")}</Button>
</div>
DOM and accessibility
The default editor has role combobox, aria-haspopup="tree", aria-expanded, aria-controls and an active descendant. components.input receives these in attributes; the owner handles accessibility for components.root. The popup contains treeitems and checkboxes; aria-label or FormItem supplies the accessible name.
Arrows move the active node and expand branches, Enter selects, Escape closes the popup. The search preserves the visibility of the parents of the matched nodes. Unavailable branches and selectable=false limit the corresponding actions.
The panel class is specified via classNames.popup.root; position example shows its outline. classNames and styles support control, tag and popup slots, including functions receiving info.props. treeTitleRender, icon and switcherIcon provide node content. Use the tokens below to style the tree.
Registration tokens
All seven component tokens are checked against ant.design and applied via theme.components.TreeSelect. The outer field also uses Select component tokens. The nested provider isolates the design from neighboring examples.
<script lang="ts">
import { ConfigProvider, TreeSelect } from '@woodger/antd';
</script>
<ConfigProvider theme={{
components: {
TreeSelect: {
titleHeight: 36,
switcherSize: 24,
indentSize: 28,
nodeHoverBg: '#f9f0ff',
nodeHoverColor: '#531dab',
nodeSelectedBg: '#722ed1',
nodeSelectedColor: '#fff'
}
}
}}>
<TreeSelect
aria-label={("TreeSelect Tokens")}
treeDefaultExpandAll
defaultValue="button"
style="width:min(100%,320px)"
treeData={[
{
value: 'ui', title: "Interface", children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
]
}
]}
/>
</ConfigProvider>
| Token | Purpose |
|---|---|
indentSize | Tree level indentation. |
switcherSize | Width of the branch switch area. |
titleHeight | The node's row height. |
nodeHoverBg | Node background when hovered. |
nodeHoverColor | Node hover color. |
nodeSelectedBg | Background of the selected node. |
nodeSelectedColor | Color of the selected node. |
Common tokens of the current topic
Values are read through theme.useToken() and react to section settings.
| Token | Current value |
|---|---|
colorBgContainer | #ffffff |
colorBgContainerDisabled | rgba(0,0,0,0.04) |
colorBgElevated | #ffffff |
colorBgTextHover | rgba(0,0,0,0.06) |
colorBorder | #d9d9d9 |
colorFillQuaternary | rgba(0,0,0,0.02) |
colorPrimary | #2f54eb |
colorPrimaryBorder | #adc6ff |
colorPrimaryHover | #597ef7 |
colorSplit | rgba(5,5,5,0.06) |
colorText | rgba(0,0,0,0.88) |
colorTextDisabled | rgba(0,0,0,0.25) |
colorTextQuaternary | rgba(0,0,0,0.25) |
colorWhite | #fff |
borderRadius | 6 |
borderRadiusSM | 4 |
controlInteractiveSize | 16 |
controlItemBgActiveDisabled | rgba(0,0,0,0.15) |
controlItemBgHover | rgba(0,0,0,0.04) |
fontFamily | -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
'Noto Color Emoji' |
fontSize | 14 |
fontSizeLG | 16 |
fontWeightStrong | 600 |
lineHeight | 1.5714285714285714 |
lineType | solid |
lineWidth | 1 |
lineWidthBold | 2 |
lineWidthFocus | 3 |
marginXS | 8 |
motion | true |
motionDurationFast | 0.1s |
motionDurationMid | 0.2s |
motionDurationSlow | 0.3s |
motionEaseInBack | cubic-bezier(0.71, -0.46, 0.88, 0.6) |
motionEaseOutBack | cubic-bezier(0.12, 0.4, 0.29, 1.46) |
paddingXS | 8 |
FAQ
How to get the parent in onChange?
Map the selected value or extra.triggerValue to the original treeData or parent map. The full path is not added to extra.
Why doesn't the search call loadData?
Search filters a known tree. Expand the lazy branch outside of search, or organize a server-side search via showSearch.onSearch and updating treeData.
Why are several nodes selected at once?
treeCheckable links parent to children and enables multiple. treeCheckStrictly disables this relationship and enables labelInValue; regular multiple selects nodes without associated marks.
How to show long signatures?
Set popupMatchSelectWidth to a number or false and check the accessibility of the panel on a narrow screen. listHeight changes the viewport height; virtual controls virtualization.