TreeSelect
Selecione os nós da árvore com pesquisa, carregamento e marcas relacionadas.
Quando usar
TreeSelect Seleciona uma subdivisão, seção de documentação ou outra entrada da hierarquia. A árvore é aberta em um painel e o valor contém a chave do nó. Se o aplicativo precisar de um caminho completo e colunas de nível individual, use Cascader.
Passe o treeData embutido com exclusivo value. O título title explica a escolha para a pessoa; key pode ser definido separadamente, mas o valor do modelo é determinado value. Para árvore permanente sem campo de entrada é Tree.
CSS Prefixos TreeSelect Mostrar total ConfigProvider.prefixCls e local prefixCls sem status de reset. Controle e uso de tags Select prefix; Popup adiciona um sufixo -tree-dropdown. A árvore aninhada mantém o adaptador nativo de árvore e as classes nativas: local prefix TreeSelect não é Tree.prefixCls.
Esquemas e declarações de dados
Esquema próprio e dados planos Compare value/label/children via fieldNames e mostra treeDataSimpleMode. A pesquisa padrão usa o campo literal value, portanto, defina explicitamente showSearch.treeNodeFilterProp para o outro esquema. Os retornos de chamada de seleção e filtragem obtêm os campos personalizados originais. Simples mode Construa o padrão children a id/pId; Se você corresponder a fieldNames deixe o nome children como padrão. Os dados de entrada não são alterados.
Nós declarativos Use TreeSelect.TreeNode e nomeado TreeSelectTreeNode. treeData Tem precedência sobre os anúncios. As estratégias estão disponíveis como TreeSelect.SHOW_PARENT, show_child e show_all. Ícone e switcherIcon Aceite o conteúdo ou trecho com TreeEventNode. class/style, data-* e aria-* aplique à string; styles.popup.item se sobrepõe ao seu próprio estilo.
Valor do nó
Único Retorna uma string ou uma chave numérica. multiple Retorna uma matriz de chaves. Para labelInValue em vez da chave, o objeto com value e label é usado em vez da chave; treeCheckStrictly Ativa este formato automaticamente.
| Tarefa | Configuração | Exemplo |
|---|---|---|
| Selecione um nó | treeData, value, onChange |
Selecione o nó de treeData |
| Selecionar nós independentes | multiple |
Múltiplos nós |
| Marque uma ramificação com descendentes | treeCheckable |
Marcas relacionadas |
| Marque caixa de seleção independentemente | treeCheckStrictly |
Independente |
| Receba a chave junto com a assinatura | labelInValue |
Assinatura |
O controle gerenciado obtém value e relata uma nova seleção via onChange. Ao contrário dos componentes com bind:value, aqui o próprio aplicativo atribui o resultado ao seu estado. defaultValue Define o valor local inicial. Relatórios de limpeza única undefined, multiple — array vazio; O exemplo básico normaliza a falta de escolha em null.
O segundo argumento onChange contém assinaturas ou null para o formato labelInValue, o terceiro é triggerValue. Esta é a chave do nó que causou a alteração, não o caminho pai. Para o modo, crie um mapa dos pais usando treeData com antecedência.
Marcas relacionadas
treeCheckable Inclui multiple e a relação dos pais com filhos. Show_Child retorna os nós marcados finais, show_parent combina a ramificação completa, show_all inclui pai e filho. Comparação da estratégia Mostra a diferença nos resultados; A estratégia afeta o modelo emitido, não apenas a assinatura.
treeCheckable Toma TreeSelectCheckableContent: boolean, texto, números, bigint, snippet, arrays aninhados, iteráveis e Promise. Apenas a verdade do valor JavaScript é usada. false, null, undefined, "", 0, -0, NaN e 0n Não inclua marcas; [], snippet e Promise incluem caixas de seleção padrão. O conteúdo não é emitido: o snippet não é chamado, iterável não, Promise não é esperado.
Conteúdo treeCheckable Permite comparar sinalizadores. O exemplo incluiu explicitamente multiple, portanto, a matriz de valores selecionados também é salva quando as marcas são desativadas.
treeCheckStrictly Desabilita o link Marcas e retorna objetos com value e label. Ao alterar o modo, combine o tipo de status com o novo formato. Para multiple normal, sem caixa de seleção, os nós são selecionados de forma independente.
selectable=false Proíbe a escolha do cabeçalho enquanto mantém a abertura da ramificação. disabled Bloqueia o nó, disableCheckbox desativa a marca separadamente, checkable=false remove sua caixa de seleção. O exemplo básico permite que você abra a "interface" sem escolher esse cabeçalho.
Limite de seleção
Limite de seleção TreeSelect Mostra maxCount para multiple Caixa de seleção vinculada e treeCheckStrictly. Os valores iniciais e gerenciados não são cortados quando o limite é reduzido; Valores desconhecidos também são levados em consideração. Você pode desmarcar ou limpar a seleção depois de atingir o limite. Este é o limite de escolha, não o número de tags visíveis: maxTagCount Limita as tags visíveis.
Explícito showCheckedStrategy=SHOW_PARENT Desativa o limite diferente de zero. Show_All o desabilita sem treeCheckStrictly; Para o normal multiple Não defina essa estratégia explicitamente se precisar de um limite. Show_Child e Strict mantêm a restrição. maxCount=0 Proíbe novos valores mesmo com show_parent/show_all; Em single, o limite não se aplica.
Para show_child, a ramificação pai pode ficar indisponível se seus filhos diretos não forem colocados dentro do limite. Além disso, é verificado o número total de valores após a marca associada. A tentativa de seleção pode causar onSelect/onDeselect sem onChange se o conjunto total exceder o limite diferente de zero. Alterar maxCount Salva a seleção atual; O modo de comutação no exemplo o limpa explicitamente para corresponder ao formato de chaves e objetos estritos.
Divulgação com cabeçalho
Divulgação TreeSelect Cabeçalho Mostra treeExpandAction=false, click e doubleClick. Por padrão, o cabeçalho seleciona apenas um nó. treeExpandedKeys e onTreeExpand Controle a divulgação, independentemente de value; O modo de mudança salva o status.
em click onTreeExpand O modo é chamado antes de onChange/onSelect. Em multiple, o duplo clique real primeiro faz duas escolhas normais e abre a ramificação. Ctrl/Meta/Shift Suprime o cabeçalho de abertura, mantendo a seleção. Switcher, caixa de seleção e teclado funcionam de forma independente; Enter Seleciona um nó ativo. explícito isLeaf=true proíbe a divulgação; disabled Proíbe a seleção, mas permite a divulgação do cabeçalho.
Pesquisa e ramificações assíncronas
showSearch Ativado por padrão para multiple. Para pesquisar títulos, passe showSearch={{ treeNodeFilterProp: 'title' }}. No mesmo objeto estão filterTreeNode, searchValue, onSearch e autoClearSearchValue. Exemplo de pesquisa Armazena a solicitação separadamente do nó selecionado e a limpa explicitamente após a seleção.
Quando o single é fechado, a busca é apagada. Para controlado searchValue Pegue a string vazia em onSearch; O nó selecionado é salvo. Em multiple Fechar o painel por si só não apaga a solicitação.
Separadores de pesquisa show tokenSeparators: string array ou função (text: string) => string[]. A partição limpa a solicitação e fecha o painel, mas não chama onChange ou onSelect e não seleciona nós pelas palavras inseridas. A escolha é feita separadamente na árvore.
Durante o IME, a divisão está esperando compositionend. Para inserir uma lista de strings, adicione \n ou \r\n à matriz delimitada ou use a função. A função retorna partes quebradas; Uma matriz vazia ou uma única string de origem significa que não há particionamento.
loadData Obtém o nó aberto e retorna Promise. Adicione carregado children a treeData até que seja concluído. Para uma ramificação que ainda não foi carregada, defina isLeaf=false, para o nó final true. Exemplo assíncrono Completa o pendente Promise e limpa o cronômetro ao sair da página.
Durante a pesquisa, loadData não é chamado. Para pesquisa de servidor, processe showSearch.onSearch e atualize treeData no aplicativo; Não espere uma solicitação separada toda vez que o filtro local corresponder. treeExpandedKeys e treeLoadedKeys Controle as ramificações abertas e carregadas separadamente dos value selecionados.
Foco e eventos
Foco e eventos TreeSelect mostra showAction=['focus'] e o log do manipulador. O painel abre na frente onFocus. uma matriz vazia ou ['click'] Salve a abertura normal com um ponteiro. Alterar showAction O campo já focado não abre o painel sozinho. autoFocus e tabIndex definir atributos de campo; Nativo autofocus e tabindex Tenha prioridade. Quando hidratado, o foco automático mantém o foco de outro controle. maxLengthComo no original, não limita a pesquisa; nativo maxlength Define a restrição do navegador.
Primeiro é chamado de campos nativos onkeydown, depois onInputKeyDown, processamento interno e raiz onKeyDown. Para cancelar uma seleção ou abrir, use event.preventDefault() em nativo onkeydown. preventDefault em onInputKeyDown Não cancela a seleção; stopPropagation Para o retorno de chamada raiz. A entrada retida seleciona uma vez para keyup ou blur. No campo ReadOnly, o espaço abre o painel; Escape fecha. Pressionar Enter/Espaço no botão de limpeza não é transferido para a raiz onKeyDown.
onFocus/onBlur Seja real focusin/focusout. Os retornos de chamada de root obtêm currentTarget raiz real, div padrão; Manipuladores de editor nativo - entrada ou textarea. O painel pop-up tem seu próprio limite de evento DOM. Fechar com o teclado e a prensagem externa é atrasado até a raiz key/blur retorno de chamada. No servidor de retorno de chamada, autofocus e os cronômetros não iniciam.
No exemplo do evento, você pode alternar single/multiple e pesquisar. Pressionar novamente o campo único sem pesquisar fecha o painel; Com uma pesquisa, ele o deixa aberto. Em multiple Pressionar a entrada salva o painel aberto e o alterna para uma área de campo livre. Limpeza de mouse único fecha o painel atrasado; Em multiple Salva seu status. onFocus/onBlur e onClick Os campos não recebem um evento de popup, incluindo o conteúdo do usuário.
Etiquetas e assinaturas devolvidas
Mapeamento de tags Compara numérico e responsive maxTagCount. Este é o número de tags visíveis; Os valores completos permanecem em callbacks e FormData. maxTagTextLength apenas corta texto e assinaturas numéricas, mantendo tooltip e etiquetas completos. Snippets e arrays permanecem conteúdo opaco. Tags responsivas são medidas após a montagem; No servidor, eles ficam ocultos até a medição.
tagRender recebe TreeSelectTagInfo: label é chamado através de render, closable/onClose Gerencie a remoção. O contador tem isMaxTag=true e não contém value/index/onClose. maxTagPlaceholder Obtém registros omitidos completos. Em treeTitleRender label em onChange torna-se um trecho vinculado: está no modo normal em rótulos, em labelInValue/strict — na gravação value e rótulos é null. Sua assinatura do nó Salva o snippet e envia-o após o campo desmontagem. Para exibir, verifique typeof label === 'função'; JSON.stringify Não mostra o conteúdo do trecho.
Campo, painel e design
Campo e slots de painel Mostrar prefix, suffix e popupRender. suffix recebe open, focado, searchValue, showSearch e loading; Ele tem prioridade sobre suffixIcon e null/undefined Retorna a seleção de ícones padrão. suffixIcon=null Oculta a seta. removeIcon Altera o ícone normal da tag. allowClear Pega o objeto com clearIcon e o nome disponível label. Limpar uma pesquisa não vazia causa onSearch com uma string vazia.
FormItem.hasFeedback Adiciona um ícone de verificação ao lado da seta padrão. suffixIcon=null Oculta a seta, mas salva o feedback. OWN suffix Substitui o conteúdo desta área e não adiciona feedback automaticamente.
em popupRender Chame o menu passado trecho para produzir a árvore original. O campo aninhado pode obter foco e salvar o rascunho entre as aberturas do painel. Semantic styles Mostrar objetos e funções classNames/styles. Os slots de campo incluem root,prefix,input,suffix,clear,content,placeholder, item, itemContent e itemRemove; O pop-up contém root, item, itemTitle e itemSwitcher. Funções são permitidas propriedades. CSS Especificado por strings. ConfigProvider.treeSelect Conjuntos variant, classNames, styles e switcherIcon; As classes locais são combinadas com o provedor, a string local do slot pop-up substitui o estilo correspondente. A entrada aninhada do provedor substitui o todo pai.
onPopupVisibleChange, popupStyle,choiceTransitionName e local direction são aceitos, mas não mudam o comportamento. Para eventos, use onOpenChange, para design — styles.popup.root, para RTL — ConfigProvider.direction. Os valores originais estão disponíveis em retornos de chamada semânticos. Nativo HTML dir Permanece um atributo separado.
Alinhamento do Painel
Alinhamento do Painel TreeSelect Compare popupAlign e builtinPlacements. O primeiro parâmetro substitui os campos da posição selecionada; offset, targetOffset e overflow são completamente substituídos. As porcentagens em offset são calculadas a partir do painel, em targetOffset — do campo.
builtinPlacements Substitui completamente o cartão de quatro posições, incluindo um objeto explicitamente vazio. Se não houver uma entrada selecionada, a centralização será usada, não a entrada padrão do mapa anterior.
ConfigProvider.popupOverflow Seleciona a área do mapa padrão: viewport ou área do documento scroll. Exemplo geral Mostra herança e viewport explícita. O próprio builtinPlacements, incluindo um cartão vazio, substitui o padrão; Local popupAlign.htmlRegion tem prioridade. A mudança de modo geral atualiza o mapa para o próximo recálculo, mantendo as coordenadas atuais.
Open Panel salva o alinhamento calculado até placement Alteração, tamanho do campo ou tamanho do painel, resize janela ou rolagem do ancestral. Alterar o mapa por si só não recalcula as coordenadas. Alterar popupAlign Causa um recálculo imediato somente se não houver uma entrada de cartão selecionada.
Animação do Painel
Animação do Painel TreeSelect Mostra a transição padrão, seu nome CSS, animation e desative a transição nomeada. transitionName=undefined Seleciona o prefixo de deslizamento padrão ConfigProvider; transitionName="" Desabilita a transição nomeada. Não vazio animation tem precedência e forma um nome do prefixo Select, -dropdown- e seu valor.
Para nome próprio defina CSS entrada e saída; O exemplo usa fade. Completar o efeito CSS completa a fase correspondente. O nome sem CSS não recebe um cronômetro de conclusão artificial. O painel salva o DOM após sair, a reabertura das interrupções fechando e a pesquisa multiple é salva. Essas configurações referem-se ao painel, não à abertura dos galhos das árvores.
theme.token.motion=false Desabilita o início da transição nomeada quando aberta. Alterar a configuração ou o nome durante a fase já iniciada não o força.
eigen
components.root Substitui o campo: tags padrão, afixos e components.input não são exibidos. Em root Exemplo Button, ele mostra a assinatura selecionada e recebe uma ária para abrir a árvore. Ao remover o slot raiz, o seletor normal é retornado com o valor atual.
components.input apenas substitui o editor, mantendo o design do seletor, tags e suffix. TextArea Editor Mostra a mudança de editor, tags responsivas e pedidos de retornos de chamada. A pesquisa e o valor selecionado permanecem dados diferentes.
Quando multiple e maxTagCount="responsive" O próprio editor está envolvido na marcação e pode obter um posicionamento absoluto suffix. Redimensionar um campo ou editor atualiza o número de tags visíveis. O painel retém a ligação ao campo em resize e rolagem, inclusive no RTL.
Snippet obtém attributes e register. Passe os atributos para o elemento DOM real e registre-o via {@attach register}. Para o componente de biblioteca, você pode registrar um objeto com inputElement, nativeElement e usando métodos focus/blur. A limpeza retornada é usada em $effect; Refs são removidos ao substituir ou desmontar. Formulário de exemplo Passa os atributos para Input, mantém a conexão do campo com TreeSelect e não adiciona um segundo valor de formulário.
Objeto { render, props } Adiciona atributos próprios. Na entrada, eles têm prioridade e os retornos de chamada ficam na frente dos internos; Os atributos internos de raiz são prioridade e os retornos de chamada internos são os primeiros. Aplicar atributos já combinados para salvar manipuladores. Para cancelar o processamento do teclado, use nativo onkeydown TreeSelect.
Parâmetros RootElement e EditorElement Refine os tipos de eventos e refs. bind:nativeElement Retorna a raiz atual, bind:inputElement — input ou textarea; Com o slot raiz, não há editor. Removido o slot — obtive o padrão div/input. A raiz nativa é responsável por exibir as restrições de valor, ARIA e nativa, incluindo disabled.
Virtualização e rolagem
popupMatchSelectWidth Repete a largura do campo em true, ajusta o painel para o conteúdo em false ou define a largura em px por número. A largura do campo permanece o mínimo. Falta de suporte e undefined Herdar ConfigProvider.popupMatchSelectWidth. Largura total do painel Compara herança com true aninhado e número local Select.
Árvore grande Contém 600 nós. virtual Herdado de ConfigProvider.virtual e habilitado por padrão. listHeight Limita a viewport, listItemHeight Define a estimativa inicial da altura da linha, listItemScrollOffset adiciona recuo ao mover para o nó ativo. popupMatchSelectWidth=false Desativa a virtualização; O valor numérico define a largura do painel. A propriedade é herdada de ConfigProvider se não for definido localmente.
via bind:this Disponível TreeSelectRef com focus, blur e scrollTo. O método pega as coordenadas key/index com align e offset. Para ir para a ramificação autoExpand Revela seu caminho interno se a divulgação não for especificada em Props. onPopupScroll Obtém o evento de árvore viewport. Setas e Enter continuam a trabalhar com o nó ativo; aria-activedescendant aponta para uma string enquanto ela está presente no DOM.
showScrollBar é aceito como uma propriedade herdada, mas não é passado para a árvore e não altera a rolagem. Não o use para controlar a barra de rolagem TreeSelect.
Exibição e forma
treeTitleRender e switcherIcon aceite Svelte trechos. Assinaturas próprias Altere a exibição do nó sem alterá-lo value. popupMatchSelectWidth Define a largura do painel, listHeight — altura; Para assinaturas longas, verifique o painel em uma tela estreita.
TreeSelect Suporta virtualização, esquemas de campo, simples mode, tags, slots de painel e semântica styles. O conjunto completo suportado é fornecido em API.
em Formulário de assinatura onChange Atualizações form.setFieldValue e reset restaurações initialValues. label Especifica o nome do campo disponível. As setas movem o foco em uma árvore, entra seleciona um nó, escapa fecha pop-up; focus/blur Disponível por meio de uma instância de componente.
Design TreeSelect Usa Tokens de design (design tokens) Tema atual.
Exemplos
Selecione o nó de treeData
A árvore é definida via treeData. Single Retorna a chave do nó selecionado; A interface pai abre, mas não está selecionada.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", disabled: true }
];
let value = $state<TreeSelectValue>(null);
</script>
<TreeSelect
aria-label={("Seção básica")}
{treeData}
{value}
treeDefaultExpandAll
allowClear
placeholder={("Selecionar seção")}
onChange={next => { value = next ?? null; }}
/>
<p><output aria-label={("Nó selecionado")}>{JSON.stringify(value)}</output></p>
Múltiplos nós
multiple Selecione nós de forma independente. As assinaturas selecionadas formam tags; Remoção da etiqueta altera o modelo.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", disabled: true }
];
let value = $state<TreeSelectValue>(['button']);
</script>
<TreeSelect
aria-label={("Múltiplas seções")}
{treeData}
{value}
multiple
treeDefaultExpandAll
allowClear
showSearch={{ treeNodeFilterProp: 'title' }}
onChange={next => { value = next; }}
/>
<p><output
aria-label={("Vários nós selecionados")}
>{JSON.stringify(value)}</output></p>
Marcas relacionadas
treeCheckable Inclui multiple e a relação dos pais com filhos. Por padrão, show_child retorna os nós finais.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", disabled: true }
];
let value = $state<TreeSelectValue>([]);
</script>
<TreeSelect
aria-label={("Seções relacionadas")}
{treeData}
{value}
treeCheckable
treeDefaultExpandAll
onChange={next => { value = next; }}
/>
<p><output
aria-label={("Nós selecionados relacionados")}
>{JSON.stringify(value)}</output></p>
Conteúdo treeCheckable
Texto, array vazio e Snippet inclui caixa de seleção padrão. O conteúdo não é exibido; multiple Salva a matriz de valores selecionados.
<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={("Valor treeCheckable")}
options={['true', 'false', '"checkbox"', '[]', 'Snippet']}
bind:value={flag}
/>
</div>
<TreeSelect
aria-label={("Seleção com sinalizador treeCheckable")}
{treeData}
treeCheckable={flag === 'Snippet' ? checkboxContent : flags[flag]}
{value}
multiple
showSearch={false}
treeDefaultExpandAll
onChange={next => { value = next; }}
/>
<p><output aria-label={("Nós selecionados com treeCheckable")}>
{JSON.stringify(value)}
</output></p>
Alterar o limite salva a seleção, alterando o modo neste exemplo. show_parent e não string show_all Desativar limite diferente de zero; maxCount=0 Proíbe uma nova escolha.
Limite de seleção TreeSelect
maxCount Limites multiple e caixa de seleção. Compare estratégias e rigorosos; Os valores iniciais acima do limite são salvos.
<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: ("dados"), 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>{("Modo limite")} <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={("Seleção com limite TreeSelect")}
{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={("Valor de limitação TreeSelect")}
>{JSON.stringify(value)}</output></p>
<p>
{("Alterar o limite salva a seleção, alterando o modo neste exemplo. show_parent e não string show_all Desativar limite diferente de zero; maxCount=0 Proíbe uma nova escolha.")}
</p>
<style>
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-block-end: 12px;
}
</style>
SHOW_ALL
SHOW_PARENT
SHOW_CHILD
Estratégia de nós marcados
show_all Mostra pais e descendentes, show_parent recolhe a ramificação, show_child deixa as folhas.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", 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={("Estratégia TreeSelect " + String((strategy)) + "")}
{treeData}
treeCheckable
showCheckedStrategy={strategy}
defaultValue={['button', 'input']}
treeDefaultExpandAll
/></div>
{/each}
</div>
Independente
treeCheckStrictly Desativa os pais e filhos e inclui labelInValue. O resultado são objetos com value e 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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", disabled: true }
];
let value = $state<TreeSelectValue>([]);
</script>
<TreeSelect
aria-label={("Seções independentes")}
{treeData}
{value}
treeCheckStrictly
treeDefaultExpandAll
onChange={next => { value = next; }}
/>
<p><output
aria-label={("Nós selecionados independentes")}
>{JSON.stringify(value)}</output></p>
Assinatura
labelInValue Retorna um objeto em vez de uma chave simples. A tecla numérica retém o tipo number.
<script lang="ts">
import { TreeSelect, type TreeSelectValue } from '@woodger/antd';
let value = $state<TreeSelectValue>(null);
</script>
<TreeSelect aria-label={("Seção com assinatura")} treeData={[{
value: 10,
title: "Documentação"
}, { value: 20, title: "Exemplos" }]}
{value} labelInValue allowClear onChange={next => { value = next ?? null; }} />
<p><output aria-label={("Selecione o objeto do nó")}>{JSON.stringify(value)}</output></p>
Pesquisar por assinatura
showSearch Especifica o searchValue controlado e filtrando por title. As correspondências aninhadas salvam a ramificação pai.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", disabled: true }
];
let value = $state<TreeSelectValue>(null);
let search = $state('');
function handleChange(next: TreeSelectValue) {
value = next ?? null;
search = '';
}
</script>
<TreeSelect aria-label={("Pesquisar a seção")} {treeData} {value} treeDefaultExpandAll
showSearch={{
treeNodeFilterProp: 'title',
searchValue: search,
onSearch: next => { search = next; }
}}
notFoundContent={("Seções")} onChange={handleChange} />
<p><output aria-label={("Pesquisa e seção selecionada")}>{(search
|| ("Pesquisa vazia"))}; {JSON.stringify(value)}</output></p>
Pesquisa:
Selecionado:
Separadores de pesquisa
tokenSeparators Pega uma matriz ou função. O separador apaga a pesquisa e fecha o painel, salvando a seleção; Esta não é uma escolha automática de nós.
<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>{("Separadores de pesquisa")} <select bind:value={splitter}>
<option value="array">{("vírgula e envoltório de linha")}</option>
<option value="function">{("Função: ponto e vírgula")}</option>
</select></label>
<Button onclick={() => { search = ''; value = ['button']; }}>
{("Redefinir o exemplo do delimitador")}
</Button>
</div>
<TreeSelect
aria-label={("Pesquisar TreeSelect com delimitadores")}
{treeData}
{value}
multiple
{tokenSeparators}
showSearch={{
searchValue: search,
treeNodeFilterProp: 'title',
onSearch: next => { search = next; }
}}
onChange={next => { value = next ?? []; search = ''; }}
/>
<p>{("Pesquisa: ")}<output aria-label={("Pesquise com delimitadores")}>{search
|| ("Pesquisa vazia")}</output></p>
<p>{("Selecionado: ")}<output
aria-label={("Nós selecionados com delimitadores")}
>{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>
Carregamento assíncrono
loadData Retorna Promise e atualizações treeData. A pesquisa não chama o carregador. Temporizador e espera Promise Termina na desmontagem.
<script lang="ts">
import { onDestroy } from 'svelte';
import { TreeSelect, type TreeSelectNode } from '@woodger/antd';
let treeData = $state<TreeSelectNode[]>([{ value: 'catalog', title: "Catálogo", 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: "Catálogo", isLeaf: false, children: [
{ value: 'guides', title: "Manual", isLeaf: true }
] }];
pending = false;
timer = undefined;
finish = undefined;
resolve();
}, 600);
});
}
onDestroy(() => {
clearTimeout(timer);
finish?.();
});
</script>
<TreeSelect
aria-label={("Seção de download")}
{treeData}
loadData={handleLoad}
placeholder={("Expandir catálogo")}
/>
<p><output aria-label={("Status de carregamento da árvore")}>{(pending ? "Carregando…" : "Catálogo pronto")}</output></p>
Ctrl, Meta e Shift salvam a ação de seleção sem rumo. O botão de abertura e o teclado funcionam separadamente.
Divulgação TreeSelect Cabeçalho
treeExpandAction: false, click ou doubleClick. A seleção e a divulgação são controladas separadamente; O modo de mudança salva o status.
<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={("Divulgação TreeSelect Cabeçalho")}
{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 e Shift salvam a ação de seleção sem rumo. O botão de abertura e o teclado funcionam separadamente.")}
</p>
Linhas das árvores e switch
treeLine Mostra as conexões, showLeafIcon controla as folhas. switcherIcon recebe TreeEventNode; treeIcon Inclui ícones de nós.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", disabled: true }
];
</script>
{#snippet switcher(node: TreeEventNode)}<span aria-hidden="true">{(node.expanded ? '−' : '+')}</span>{/snippet}
<TreeSelect
aria-label={("Árvore com linhas")}
{treeData}
treeDefaultExpandAll
treeLine={{ showLeafIcon: true }}
treeIcon
switcherIcon={switcher}
/>
Posição da árvore
Quatro valores placement Defina o posicionamento preferencial do pop-up. classNames.popup.root Adiciona classe de quadro de painel.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", 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={("Posição da árvore " + String((placement)) + "")}
{treeData}
{placement}
classNames={{ popup: { root: 'tree-select-example-popup' } }}
placeholder={(placement)}
/>
{/each}
</div>
popupAlign.offset: [16, 12]
builtinPlacements: Painel 16 px
Alinhamento do Painel TreeSelect
PopupAlign Altera o deslocamento, builtinPlacements Substitui o mapa de posição. Compare o recuo de dois campos.
<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={("Offset do painel TreeSelect")}
{treeData}
placement="bottomLeft"
popupAlign={{ offset: [16, 12] }}
placeholder={("Componente de seleção")}
treeDefaultExpandAll
/>
</div>
<div>
<p><code>builtinPlacements</code>: {("Painel 16 px")}</p>
<TreeSelect
aria-label={("Posição própria TreeSelect")}
{treeData}
placement="bottomLeft"
builtinPlacements={placements}
placeholder={("Componente de seleção")}
treeDefaultExpandAll
/>
</div>
</div>
Animação do Painel TreeSelect
Transição padrão, nome próprio CSS e animation. Empty transitionName Desabilita a transição nomeada; animation tem prioridade.
<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={("Transição do painel TreeSelect")}
options={([
{ value: 'default', label: "Transição Padrão" },
{ value: 'transition', label: 'transitionName' },
{ value: 'animation', label: 'animation' },
{ value: 'none', label: "Sem animação" }
])}
bind:value={mode}
/>
</div>
<TreeSelect
aria-label={("TreeSelect Com Animação em Painel")}
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; }}
/>
Opções de design
outlined, filled, borderless e underlined Use uma árvore e seleção de nós.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", 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={("Opção TreeSelect " + String((variant)) + "")} {treeData} {variant} placeholder={(variant)} />{/each}
</div>
Status de validação
error e warning Defina o status. Um campo completamente inacessível e um nó inacessível são mostrados separadamente.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", disabled: true }
];
</script>
<style>
.examples {
display: grid;
gap: 16px;
}
</style>
<div class="examples">
<TreeSelect
aria-label={("Seção de erro")}
{treeData}
status="error"
placeholder={("Erro")}
/>
<TreeSelect
aria-label={("seções de aviso")}
{treeData}
multiple
status="warning"
placeholder={("Aviso")}
/>
<TreeSelect
aria-label={("Árvore indisponível")}
{treeData}
disabled
defaultValue="button"
/>
</div>
Dimensões
large, medium e small. O campo sem local size herda as configurações da partição.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", 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={("Tamanho TreeSelect " + String((size)) + "")} {treeData} {size} placeholder={(size)} />{/each}
</div>
Sua assinatura do nó
treeTitleRender — Svelte Snippet. Ele altera a assinatura na árvore e o valor selecionado, salvando a chave.
<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: "dados", children: [
{ value: 'table', title: 'Table' }, { value: 'select', title: 'Select' }
] },
{ value: 'locked', title: "Seção indisponível", 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={("Árvore com suas assinaturas")}
{treeData}
treeDefaultExpandAll
treeTitleRender={title}
defaultValue="button"
onChange={(_value, labels) => {
const label = labels?.[0];
savedLabel = typeof label === 'function' ? label : undefined;
}}
/>
{/if}
<Button
onclick={() => { mounted = !mounted; }}
>{("Mostrar ou ocultar TreeSelect")}</Button>
</Flex>
<output
aria-label={("Assinatura salva TreeSelect")}
>{#if savedLabel}{@render savedLabel()}{/if}</output>
<style>
output {
display: block;
margin-top: 12px;
}
</style>
fieldNames
treeDataSimpleMode
Esquema próprio e dados planos
fieldNames Correspondendo aos campos do registro; treeDataSimpleMode Construa a hierarquia id/pId. O retorno de chamada obtém os campos originais.
<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={("Campos próprios TreeSelect")} 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={("Entrada Original TreeSelect")}>{selected}</output>
</div>
<div>
<p>treeDataSimpleMode</p>
<TreeSelect aria-label={("Dados planos TreeSelect")} 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>
Campo e slots de painel TreeSelect
prefix, suffix, ícone de limpeza e popupRender. O campo dentro do painel salva o rascunho ao reabrir.
<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={("Rascunho TreeSelect")} bind:value={draft} />
</div>
{/snippet}
{#snippet suffix(info: TreeSelectSuffixInfo)}<span
aria-hidden="true"
>{info.open ? '▴' : '▾'}</span>{/snippet}
<TreeSelect aria-label={("Painel Próprio TreeSelect")} {treeData} treeDefaultExpandAll
prefix="UI" {suffix} popupRender={popup}
allowClear={{ clearIcon: '×', label: ("Limpar TreeSelect") }}
showSearch={{ treeNodeFilterProp: 'title' }} />
<style>
.popup-footer {
padding: 8px;
border-top: 1px solid var(--ant-color-border-secondary);
}
</style>
Semantic styles TreeSelect
Configurações ConfigProvider, função styles, placeholder e switcher. O slot local se sobrepõe aos estilos do provedor.
<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}
/>{("Selecionar Painel TreeSelect")}</label>
{#snippet placeholder()}<em>{("Selecione o componente")}</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={("Design TreeSelect")}
{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>
Árvore grande TreeSelect
600 nós, ConfigProvider.virtual, estimativa de altura da linha e rolando até a chave até 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; }} >{("Abra Big Tree")}</Button>
<Button onclick={() => scrollTo({ key: 480, align: 'top' })}>scrollTo 480</Button>
<Button onclick={() => scrollTo({ top: 0 })}>{("Para o início da árvore")}</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>
Nós declarativos TreeSelect
TreeSelect.TreeNode e nomeado TreeSelectTreeNode, estratégia estática, ícones e design de linha.
<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={("Nós declarativos TreeSelect")}
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>
Foco e eventos TreeSelect
showAction Abre a árvore em foco. O log mostra a ordem de nativos, input e retornos de chamada de raiz e cancelamento de entrada.
<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>{("Modo de campo de evento")} <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}
/>{("Pesquisa no campo Evento")}</label>
<label><input type="checkbox" bind:checked={focusAction} />showAction=['focus']</label>
<label>{("Cancelar Digite")} <select bind:value={cancellation}>
<option value="none">{("Sem cancelamento")}</option>
<option value="native">onkeydown.preventDefault()</option>
<option value="hook">onInputKeyDown.preventDefault()</option>
</select></label>
<Button onclick={() => control?.focus()}>{("Foco no evento TreeSelect")}</Button>
<Button onclick={() => { events = []; }}>{("Limpar o log de eventos")}</Button>
</div>
<TreeSelect
bind:this={control}
aria-label={("Eventos TreeSelect")}
{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={("Seleção em Eventos de Exemplo")}
>{JSON.stringify(value)}</output></p>
<pre aria-label={("Registro de Eventos TreeSelect")}>{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>
Selecionado:
nativeElement:
Root Próprio TreeSelect
components.root Substitui o campo completamente. Button Obtém atributos e registra o DOM; A assinatura e a ária são definidas pelo proprietário.
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 ?? ("Componente de seleção"); }); </script> {#snippet root(context: TreeSelectRootContext<HTMLButtonElement>)} <ComponentButton {context} {label} /> {/snippet} <div class="controls"> <Checkbox bind:checked={custom}>{("Root Próprio TreeSelect")}</Checkbox> <Button onclick={() => control?.focus()}>{("Foco na raiz TreeSelect")}</Button> <Button onclick={() => { value = null; open = false; }} >{("Redefinir a raiz")}</Button> </div> <TreeSelect id="tree-select-components-root" aria-label={("Seleção via raiz própria")} {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>{("Selecionado: ")}<output aria-label={("Escolha de raiz própria")}>{JSON .stringify(value)}</output></p> <p>nativeElement: <output aria-label={("DOM raiz nativo")}>{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>
Selecionado:
inputElement:
Próprio Editor TreeSelect
components.input Apenas substitui o editor. TextArea salva tags e posicionamento responsivo; A revista mostra propriedades, nativos, gancho e retornos de chamada de root.
<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}>
{("Editor de área de texto em TreeSelect")}
</Checkbox>
</div>
<TreeSelect
aria-label={("Seleção com o próprio 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>{("Selecionado: ")}<output
aria-label={("Seleção do editor próprio")}
>{JSON.stringify(value)}</output></p>
<p>inputElement: <output aria-label={("Dom Own Editor")}>{inputElement
?.tagName
?? '—'}</output></p>
<pre aria-label={("Editor Processador Pedido")}>{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>
Próprio Editor na forma
Input Registre composto ref com focus/blur. Form Salva o nó selecionado, verifica o campo e recria o editor em 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={("Formulário com o Editor Próprio TreeSelect")} onFinish={values => { result = JSON.stringify(values.component); }} > <FormItem name="component" label={("Componente com Editor Próprio")} rules={([{ required: true, message: "Selecione um componente no campo Editor." }])} > <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">{("Salvar o componente")}</Button> <Button onclick={() => form.focusField('component')}> {("Foco do editor via formulário")} </Button> <Button htmlType="reset" onclick={() => { result = '—'; }} >{("Componente de redefinição")}</Button> </div> </Form> <p><output aria-label={("Resultado do formulário")}>{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} />
Assinatura de partição no formulário
Formulário original da avaliação: marcas relacionadas, pesquisa, necessário Seleção, submit e reset. Form Armazena as chaves.
<script lang="ts">
import { TreeSelect, Form, FormItem, Button, createForm } from '@woodger/antd';
const data = [
{
value: 'components',
title: "Componentes",
children: [
{ value: 'button', title: 'Button' },
{ value: 'input', title: 'Input' },
{ value: 'select', title: 'Select' }
]
},
{
value: 'docs',
title: "Documentação",
children: [{ value: 'start', title: "Primeiros passos" }]
}
];
const form = createForm<{ topics: string[] }>(
{
initialValues: { topics: ['button'] },
rules: ({ topics: [{ required: true, message: "Selecione as seções." }] })
}
);
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={("Assinatura de partição")}><TreeSelect
treeData={data}
value={form.values.topics}
treeCheckable
treeDefaultExpandAll
showSearch={{ treeNodeFilterProp: 'title' }}
allowClear
placeholder={("Selecionar seções")}
onChange={next => form.setFieldValue('topics', next)}
/></FormItem>
<div
style="
display: flex;
gap: 8px;
flex-wrap: wrap;
"
><Button
type="primary"
htmlType="submit"
>{("Salvar seções")}</Button><Button
htmlType="reset"
>{("Reinicie as seções")}</Button></div>
</Form>
<output aria-label={("Seções salvas")}>{result}</output>
</div>
Sem o controle de valor local usa geral -selecionar, pop-up — comum -tree-select-dropdown. Com prefixCls local, ambos usam o mesmo namespace e pop-up adiciona -dropdown. A árvore aninhada salva o adaptador de árvore nativa e suas próprias classes: prefixo local TreeSelect não é igual a árvore.prefixCls.
CSS Prefixos TreeSelect
namespace geral ConfigProvider e local prefixCls; O estado do componente é salvo ao alterar o nome.
<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}>{("Prefixo geral TreeSelect Suite")}</Checkbox>
<Checkbox bind:checked={local}>{("prefixo local 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 com")}
style="width:100%" treeData={[
{
value: 'project', title: "Projeto", children: [
{ value: 'docs', title: "Documentação" }, { value: 'examples', title: "Exemplos" }
]
}
]} />
<output
aria-label={("selecione TreeSelect com prefixo")}
>{JSON.stringify(value)}</output>
</div>
</ConfigProvider>
<output
aria-label={("CSS-prefixo TreeSelect")}
>{("Geral: ")}{prefix}{("; Local: ")}{(localPrefix
|| ("Do provedor"))}</output>
<p>
{("Sem o controle de valor local usa geral -selecionar, pop-up — comum -tree-select-dropdown. Com prefixCls local, ambos usam o mesmo namespace e pop-up adiciona -dropdown. A árvore aninhada salva o adaptador de árvore nativa e suas próprias classes: prefixo local TreeSelect não é igual a árvore.prefixCls.")}
</p>
</div>
API
Temas principais TreeSelect e recursos adicionais do público API. Os dados básicos e gerados a partir de árvores são combinados; Alguns exemplos mostram o alinhamento e a animação do painel.
| Tema | Exemplo ou restrição |
|---|---|
| Basic / Generate from tree data | Hierarquia treeData; Os nós declarativos são mostrados separadamente. |
| Multiple Selection | Seleção independente e remoção de tags. |
| Checkable | Relacionado; Estratégias adicionais e estritas são mostradas separadamente. |
| Conteúdo treeCheckable | O valor do sinalizador inclui marcas sem exibir seu conteúdo. |
| Asynchronous loading | Promise, atualização e limpeza da árvore. |
| Show Tree Line | Linhas, folhas e trecho do switcher. |
| Divulgação TreeSelect Cabeçalho | Três modos treeExpandAction e controlados treeExpandedKeys. |
| Placement | Quatro posições de painel. |
| Alinhamento do Painel TreeSelect | Offset e mapa de posição próprio. |
| Animação do Painel TreeSelect | Transições padrão e próprias, desativando a animação. |
| Variants | Quatro projetos de campo. |
| Status | Erro, aviso e disabled. |
| Max Count | maxCount Limita a escolha; maxTagCount Limita apenas as tags visíveis. |
| Prefix and Suffix | prefix, suffix, suffixIcon, removeIcon e popupRender. |
| Custom semantic dom styling | Objetos e funções classNames/styles; Configurações ConfigProvider.treeSelect. |
| Foco e eventos TreeSelect | Abertura de foco, pedidos de retorno de chamada e cancelar o processamento do teclado. |
| Separadores de pesquisa | Array de delimitadores, function, insira strings e salve os valores selecionados. |
| Root Próprio TreeSelect | Substituição de campo completo, atributos, registro DOM e retorno de raiz padrão. |
| Próprio Editor TreeSelect | TextArea em vez de input, salvando tags e pedindo manipuladores. |
| Próprio Editor na forma | Composto ref Biblioteca Input Foco no campo, validação e reset. |
| Virtual list | Strings virtuais e scrollTo por tecla. |
| TreeNode | Anúncios, ícones e atributos de string. |
| Tags | Abreviatura e posicionamento de tag responsivo. |
| Data schemas | Campos próprios e lista plana. |
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
components | Raiz substitui completamente o seletor e tem prioridade sobre a entrada. A entrada substitui o editor salvando tags e afixos. Snippet obtém atributos/registro; O objeto também recebe suportes. | TreeSelectComponents<RootElement, EditorElement> | undefined |
tokenSeparators | ReadOnly Array of Strings (text: string) => string[]. A partição limpa a pesquisa e fecha o painel sem onChange/onSelect; IME espera compositionend. | TreeSelectTokenSeparators | undefined |
showScrollBar | Aceito para compatibilidade, mas não é passado para a árvore e não altera a rolagem. | boolean | "optional" | undefined |
showAction | O foco adiciona uma abertura de foco. Array vazio e click salvar a abertura com ponteiro; Alterar os suportes com o foco já definido não abre o painel. | ('focus' | 'click')[] | undefined |
autoFocus | Campo Autofocus após a montagem; Nativo autofocus tem precedência. A hidratação mantém o foco de outro controle. | boolean | undefined |
tabIndex | Ordem de foco do teclado; Nativo tabindex tem precedência. | number | undefined |
maxLength | Como no original, não limita a pesquisa TreeSelect. Para DOM, use nativo maxlength. | number | undefined |
onInputKeyDown | Campo de gancho após nativo onkeydown. Seu preventDefault não cancela a escolha; Para cancelar, use nativo onkeydown. | DOMAttributes<EditorElement | HTMLInputElement>['onkeydown'] | undefined |
onKeyDown | Callback do teclado raiz após o processamento interno. onKeyUp Informa o lançamento da chave. | DOMAttributes<RootElement | HTMLDivElement>['onkeydown'] | undefined |
onFocus | Real focusin; onBlur Obtém focusout. currentTarget Corresponde à raiz DOM, div padrão. | DOMAttributes<RootElement | HTMLDivElement>['onfocusin'] | undefined |
onMouseDown | Evento de controle raiz; Também suportado onClick, onMouseEnter e onMouseLeave. | DOMAttributes<RootElement | HTMLDivElement>['onmousedown'] | undefined |
styles | CSS Slots semânticos; Os slots pop-up locais substituem os estilos apropriados do provedor. | TreeSelectSemanticValue<TreeSelectStyles> | undefined |
children | TreeSelect.TreeNode ou TreeSelectTreeNode; treeData Tem precedência sobre os anúncios. | Snippet | undefined |
fieldNames | Nomes de campo value, label e children. Para pesquisar sua assinatura, defina explicitamente treeNodeFilterProp. | TreeSelectFieldNames | value / label / children |
treeDataSimpleMode | Construa children por id/pId; rootPId Especifica o pai das raízes. O nome children permanece padrão. | boolean | TreeSelectSimpleModeConfig | false |
maxTagCount | Número de tags visíveis. Todos os valores selecionados são armazenados em callbacks e FormData. | number | "responsive" | undefined |
maxTagTextLength | atalhos tag texto; tooltip e retornos de chamada salvam a assinatura completa. | number | undefined |
maxTagPlaceholder | Conteúdo ou conteúdo do trecho com registros omitidos e rótulos completos. | TreeSelectTagPlaceholder | + N ... |
tagRender | label — trecho; closable/onClose Gerencie a remoção. O resumo tem isMaxTag=true sem value/index/onClose. | Snippet<[TreeSelectTagInfo]> | undefined |
popupRender | Painel próprio; Chamar menu() Salva a árvore original. Os campos aninhados podem obter foco. | Snippet<[Snippet]> | undefined |
prefix | Conteúdo na frente do campo. | TreeSelectLabel | undefined |
suffix | Conteúdo ou trecho com open, focado, searchValue, showSearch e loading; Tem prioridade sobre suffixIcon. | TreeSelectSuffix | undefined |
suffixIcon | ícone próprio; null Oculta a seta. | TreeSelectLabel | Seta padrão |
removeIcon | Ícone de remoção regular de tags. tagRender Define sua própria marcação. | TreeSelectLabel | × |
placeholder | Texto, número, matriz ou snippet campo vazio. | TreeSelectLabel | undefined |
virtual | Virtualização de strings. popupMatchSelectWidth=false Desativa. | boolean | ConfigProvider.virtual / true |
listItemHeight | Estimativa inicial da altura da linha; 0 Desativa a virtualização. | number | controlHeightSM + paddingXXS |
listItemScrollOffset | Recuo adicional ao mover para o nó ativo. | number | 0 |
popupMatchSelectWidth | true Especifica a largura do campo, false é a largura do conteúdo e desativa a virtualização. conjuntos de números px; A largura do campo permanece o mínimo. undefined Herda ConfigProvider. | boolean | number | ConfigProvider / true |
treeIcon | Inclui ícones do nó icon. A função é usada como sinalizador, o conteúdo define o nó. | TreeSelectNodeIcon | false |
switcherIcon | Conteúdo ou trecho com TreeEventNode. O valor local se sobrepõe ao provedor; false Deixa um interruptor vazio. | TreeSelectSwitcherIcon | ConfigProvider.treeSelect |
prefixCls | Prefixo local completo Select control e TreeSelect pop-up. Sem ele, são usados -select e -tree-select comuns; Com ele, ambos recebem um namespace. O adaptador nativo Tree armazena suas próprias classes. | string | ConfigProvider.prefixCls + "-select" |
classNames | campo, tag e pop-up; Objeto ou função com info.props. | TreeSelectSemanticValue<TreeSelectClassNames> | undefined |
treeData | Hierarquia com value exclusivos. Seus campos são suportados, icon, switcherIcon, class/style, data-* e aria-* linhas. | readonly Data[] | [] |
value | Chave gerenciada, objeto de assinatura ou matriz. Ao limpar o single, tome undefined como null para manter o modo controlado. bind:value Não suportado. | TreeSelectValue | undefined |
defaultValue | Inicie o valor local, leia uma vez. | TreeSelectValue | undefined |
onChange | Novo valor e extra.triggerValue. treeTitleRender Retorna label-snippets; Em labelInValue eles estão em value e rótulos é null. | (value, labels, extra) => void | — |
multiple | Seleção independente de múltiplos nós. treeCheckable e treeCheckStrictly também incluem multiple. | boolean | false |
treeCheckable | O valor é usado como sinalizador: Truthy inclui caixa de seleção padrão e multiple. Uma matriz vazia e um trecho incluem marcas; O conteúdo não é exibido. | TreeSelectCheckableContent | false |
maxCount | Limite multiple incluindo caixa de seleção/valores estritos e desconhecidos. Não corta o conjunto inicial. explícito show_parent e show_all sem limite de desativação estrito diferente de zero; 0 proíbe uma nova escolha. em single não se aplica. | number | undefined |
treeCheckStrictly | Caixa de seleção independente e automática labelInValue. | boolean | false |
showCheckedStrategy | Gerenciar tags e o resultado de uma seleção relacionada. Sem treeCheckable Use show_all. | SHOW_ALL | SHOW_PARENT | SHOW_CHILD | show_child em treeCheckable |
labelInValue | objetos { value, label, halfChecked? } em vez de teclas simples. | boolean | false |
showSearch | Objeto contém searchValue, onSearch, filterTreeNode, treeNodeFilterProp e autoClearSearchValue. Para pesquisar por assinatura, especifique title. | boolean | TreeSelectSearchConfig | single: false; multiple: true |
loadData | Carrega children com treeData Atualização. Não invocado durante a pesquisa. | (node) => PromiseLike<unknown> | — |
treeExpandedKeys | Divulgação gerenciada com onTreeExpand; treeDefaultExpandedKeys e treeDefaultExpandAll Defina o início. | readonly TreeKey[] | Estado local |
treeExpandAction | Divulgação do cabeçalho. Ctrl/Meta/Shift Suprime a abertura, mantendo a seleção. No modo de clique onTreeExpand precede onChange/onSelect. | false | "click" | "doubleClick" | false |
treeLoadedKeys | Gerenciado nós carregados com onTreeLoad. | readonly TreeKey[] | Estado local |
treeLine | Conexão em árvore e exibição de folhas. treeIcon Inclui ícones de nós. | boolean | { showLeafIcon: TreeSelectSwitcherIcon } | false |
treeTitleRender | Conteúdo do nó e rótulos retornados. O snippet pode ser salvo e emitido após o campo desmontagem. | Snippet<[Data]> | Assinatura do nó |
allowClear | Limpeza e onClear. O objeto define clearIcon e o nome disponível label; A pesquisa não vazia é apagada com onSearch. | boolean | TreeSelectAllowClear | false |
open | Popup gerenciado com onOpenChange, defaultOpen Define o início. | boolean | Estado local |
listHeight | Altura da árvore da viewport. onPopupScroll Obtém este evento de contêiner. | number | 256 |
placement | Lado pop-up preferencial. popupMatchSelectWidth Define a largura, getPopupContainer — container. | topLeft | topRight | bottomLeft | bottomRight | na direção da interface |
popupAlign | Substitui os campos da posição selecionada; offset, targetOffset e overflow são totalmente substituídos. As coordenadas são salvas até o evento de recálculo. | TreeSelectPopupAlign | undefined |
builtinPlacements | Substitui completamente o mapa de posição. Um objeto vazio não restaura registros padrão; A posição ausente centraliza o painel. | Readonly<Record<string, TreeSelectPopupAlign>> | undefined |
animation | Valor não vazio Seleciona a transição do prefixo Select e do sufixo animation sobreposição transitionName. Para o próprio nome, você precisa CSS. | string | undefined |
transitionName | Nome CSS Transição do painel. undefined Seleciona o deslizamento padrão, a string vazia desativa a transição nomeada. | string | ConfigProvider.prefixCls + "-slide-up" |
onOpenChange | Relata uma solicitação para abrir ou fechar o painel. No modo gerenciado, atualize open com esse valor. | (open: boolean) => void | undefined |
onPopupVisibleChange | Aceito sem ligar. A mudança no estado do painel relata onOpenChange. | (open: boolean) => void | undefined |
popupStyle | Aceito sem uso. O design do painel é definido em styles.popup.root. | string | undefined |
choiceTransitionName | Aceito, mas o overflow atual não se aplica à animação de tags. | string | undefined |
direction | é aceito sem mudar de direção. RTL e os conjuntos de posição padrão ConfigProvider; HTML dir é um atributo separado. | ltr | rtl | ConfigProvider.direction |
size | Tamanho do campo; status — error ou warning. | large | medium | small | de ConfigProvider |
variant | Prop local → mais próximo Form.variant → ConfigProvider.treeSelect.variant → total ConfigProvider.variant → outlined. | Variant | Do contexto / delineado |
nativeElement | Ref da raiz registrada. sem components.root Retorna o div; Quando a desmontagem é apagada. | RootElement | HTMLDivElement | — |
inputElement | Ref Editor: input ou textarea. com components.root sem editor; A remoção do slot de entrada retorna a entrada padrão. | EditorElement | HTMLInputElement | — |
Os tipos completos estão no pacote. ConfigProvider.treeSelect Conjuntos variant, classNames, styles e switcherIcon. As classes locais são combinadas com as configurações do provedor; Local CSS Os slots pop-up substituem os estilos correspondentes.
Métodos
via bind:this Disponível TreeSelectRef com focus(options?), blur() e scrollTo(config). Para acessar o DOM, há bind:inputElement e bind:nativeElement.
<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={("Métodos TreeSelect")}
style="width:min(100%,240px)"
treeData={[{ value: 'docs', title: "Documentação" }]}
/>
<Button onclick={() => control?.focus()}>{("Foco TreeSelect")}</Button>
<Button onclick={() => control?.blur()}>{("Remova o foco TreeSelect")}</Button>
</div>
DOM e disponibilidade
O editor padrão tem uma função ComboBox, aria-haspopup="tree", aria-expanded, aria-controls e descendentes ativos. components.input Obtém esses atributos em atributos; Para components.root a disponibilidade é definida pelo proprietário. O pop-up contém TreeItem e CheckBox; O nome do campo disponível é definido como aria-label ou FormItem.
Setas Mova o nó ativo e abre as ramificações, insira seleções, Escape fecha o pop-up. A pesquisa mantém a aparência dos pais dos nós correspondentes. Ramos indisponíveis e selectable=false limitam as ações correspondentes.
A classe do painel é definida por meio de classNames.popup.root; Exemplo de posição Mostra seu quadro. classNames e styles Suporta slots, tags e popup incluindo funções com info.props. treeTitleRender, icon e switcherIcon Especifique o conteúdo dos nós. Para fazer uma árvore, use os tokens mostrados abaixo.
Tokens de design
Todos os sete tokens de componentes são verificados com Ant.Design e aplicados por meio de theme.components.TreeSelect. O campo externo também usa tokens de componentes Select. Um provedor aninhado isola o design de exemplos vizinhos.
<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={("Tokens TreeSelect")}
treeDefaultExpandAll
defaultValue="button"
style="width:min(100%,320px)"
treeData={[
{
value: 'ui', title: "Interface", children: [
{ value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
]
}
]}
/>
</ConfigProvider>
| Token | Atribuir |
|---|---|
indentSize | Preenchimento de nível de árvore. |
switcherSize | Largura da área de comutação de ramo. |
titleHeight | Altura da string do nó. |
nodeHoverBg | background do nó ao passar o mouse. |
nodeHoverColor | Cor do nó ao passar o mouse. |
nodeSelectedBg | Plano de fundo do nó selecionado. |
nodeSelectedColor | Cor do nó selecionado. |
Tokens comuns do tema atual
Os valores são lidos em theme.useToken() e respondem às configurações da seção.
| Token | Valor atual |
|---|---|
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
Como obter o pai em onChange?
Combine com o value ou extra.triggerValue selecionado com o original treeData ou o cartão dos pais. O caminho completo em extra não foi adicionado.
Por que a pesquisa não causa loadData?
A pesquisa filtra a árvore conhecida. Expanda a ramificação preguiçosa fora da pesquisa ou organize uma pesquisa de servidor em showSearch.onSearch e atualize treeData.
Por que vários nós são selecionados de uma só vez?
treeCheckable Vincula o pai à prole e inclui multiple. treeCheckStrictly Desativa este link e habilita labelInValue; Regular multiple Seleciona nós sem marcas vinculadas.
Como mostrar assinaturas longas?
Defina popupMatchSelectWidth número ou false e verifique a disponibilidade do painel em uma tela estreita. listHeight Altera a altura da viewport; virtual Gerencia a virtualização.