Tree
Árvores: abertura, seleção, marcas, busca, download assíncrono e teclado.
Quando usar
A árvore exibe pastas, seções de documentação ou hierarquia organizacional. As ramificações podem ser abertas, as linhas podem ser selecionadas e os nós são marcados com a caixa de seleção. Para a árvore dentro do campo de entrada compacto, use TreeSelect.
Passe o treeData embutido com o Unique Steady key. A chave identifica o nó em toda a árvore, não apenas entre seus vizinhos; title Responsável pela assinatura.
CSS Árvore de prefixo Mostrar total ConfigProvider.prefixCls e local prefixCls sem status de reset. Os nós, o switcher, a caixa de seleção e as linhas usam o prefixo da árvore. DOM, IDS ARIA, chaves selecionadas e download inacabado são salvos. TreeSelect Possui seu próprio adaptador de árvore.
Divulgação, seleção e marcas
expandedKeys, selectedKeys e checkedKeys são três estados independentes. Mudar um não deve substituir os outros dois. Para uma árvore gerenciada, leve novas chaves por meio do retorno de chamada correspondente.
| Tarefa | Configuração | Exemplo |
|---|---|---|
| Mostrar nós aninhados | treeData, defaultExpandedKeys |
árvore comum |
| Gerenciar estados de fora | expandedKeys, selectedKeys, checkedKeys |
Árvore gerenciada |
| Selecione várias linhas | multiple, onSelect |
árvore comum |
| Compare regras da caixa de seleção | checkable, checkStrictly |
Marcas relacionadas e independentes |
| Carregar nós filhos | loadData, loadedKeys |
Baixe com erro e repita |
defaultExpandedKeys, defaultSelectedKeys e defaultCheckedKeys são lidos ao criar uma árvore. defaultExpandAll também se refere ao conjunto de dados inicial. Para os dados que vieram depois, gerencie expandedKeys ou crie uma árvore depois de recebê-la.
checkable Ativa a caixa de seleção. Por padrão, as marcas são distribuídas entre os pais e os descendentes, e uma ramificação incompleta recebe uma marca parcial. checkStrictly Desabilita a conexão: onCheck Retorna o objeto checked/halfChecked. disabled O nó impede que as marcas se espalhem por si mesmo. selectable e disableCheckbox Ajuste separadamente a seleção da linha e a disponibilidade da marca.
Baixe e pesquise
loadData Obtém TreeEventNode e retorna Promise. Para uma ramificação descarregada, defina isLeaf=false; Após a resposta, adicione children a treeData e complete Promise. loadedKeys Armazene as chaves de download concluídas, onLoad Relata suas atualizações. No script gerenciado, aceite o novo loadedKeys para que o status do download corresponda aos dados.
Exemplo assíncrono Mostra o erro e a reabertura. A mensagem de erro e a solicitação pertencem ao aplicativo; Ao sair da página, libere seus cronômetros e recursos.
filterTreeNode Destaca os nós adequados em vez de remover outras linhas. Pesquisa Separadamente, calcula os pais das partidas para expandedKeys e desenha a marca através de titleRender. Com seu próprio filtro, mantenha os ancestrais e as chaves estáveis desejadas.
Design e teclado
showLine Desenha links, showIcon Ativar ícones. titleRender, icon, switcherIcon e switcherLoadingIcon aceitar Svelte trechos; TreeEventNode Contém estados de nós, incluindo expandido, selecionado e loading. Exemplo de ícones Altera a visualização sem alterar as chaves.
blockNode Alonga a string; height Especifica a viewport da janela virtual. Se virtual=false todas as strings abertas permanecerem no DOM com rolagem nativa. Revestimento API Liste as configurações disponíveis.
Arrastando nós Mostra draggable, allowDrop e onDrop para árvore/DirectoryTree incluindo RTL e janela virtual. Os dados reorganizam o aplicativo. dropToGap=false significa transferência; Para transferir entre as linhas, subtraia o último índice node.pos de info.dropPosition: você obtém -1 ou 1. dragNodesKeys contém a chave de origem e todos os descendentes. nodeDraggable=false Desabilita strings e drop strings; icon=false apenas esconde a alça. disabled Proibi o início do arrasto, mas o alvo deve ser limitado separadamente por meio de allowDrop. onDragEnter Comunica as chaves antes da abertura atrasada; O novo conjunto chega em onExpand a 800 ms.
Animação de abertura de árvore Compara o padrão collapse, própria CSS fase e motion=false. null/undefined Incluir uma transição padrão; Retorno de chamadas start/retorno ativo CSS strings, prepare pode retornar Promise. motionDeadline Completa a transição se CSS evento não chegar. A biblioteca leva em consideração o reduzido motion; theme.token.motion=false Remove a fase CSS, mantendo-se preparado. Várias alterações simultâneas expandedKeys são aplicadas sem transição. Ao virtualizar, o grupo animado é limitado à janela; Arraste, troque de dados e desmonte Cancele os retornos de chamada obsoletos.
raiz class/style e class/style nós individuais estão disponíveis. O componente Tokens de design (design tokens) em árvore opera e é atualizado de forma reativa; Tokens DirectoryTree Aplicar às linhas selecionadas da árvore de arquivos. Exemplo de tópico Salva a escolha ao alterar o design.
O foco permanece em role=tree, o nó ativo é transmitido via aria-activedescendant. As setas o movem e abrem/rolam os ramos, Home/End vão para as bordas. Enter abre uma ramificação ou seleciona uma planilha, o espaço altera a marca ou a seleção. Exemplo de teclado Mostra activeKey e foco o trabalho. bind:nativeElement Retorna a raiz externa após a montagem.
Em Tree e DirectoryTree, tabIndex define a ordem do foco. No exemplo, tabIndex={-1} faz com que a tecla Tab ignore a árvore, e o botão move o foco para ela com focus(). onFocus e onBlur indicam mudanças de foco. onKeyDown recebe o evento nativo depois de a árvore processar a tecla. onMouseDown e onContextMenu recebem eventos do rato na árvore.
Divulgação, arquivos e caminhos
Divulgação com cabeçalho Suporta expandAction=false, click e doubleClick. Ctrl/Meta/Shift Deixe apenas a escolha; O switcher e o teclado funcionam de forma independente.
Árvore de arquivos usa DirectoryTree. Por padrão, showIcon e blockNode, expandAction="click" estão habilitados. Se multiple Normal Click seleciona uma linha, Ctrl/Meta muda de tecla, Shift seleciona o intervalo de linhas visíveis. O clique repetido não remove a escolha.
Ícones de nós mostre TreeDataNode.switcherIcon e showLine.showLeafIcon como trecho. O ícone do nó se sobrepõe ao switcher comum e loading; Passe os callbacks onMouseEnter/onMouseLeave Obter Evento e atual TreeEventNode, inclusive para disabled Node.
Caminhos de dados Use createTree(dataOrGetter, config).getPath(key), não DOM ref. getPath Retorna TreeDataEntity[] da raiz ao nó; A entidade contém node, nós, key, index, pos, nível, pai e children. A chave desconhecida fornece uma matriz vazia. Para uma atualização reativa, transfira dados para Getter e Getter config.fieldNames; Substitua os links para a matriz e fieldNames. Um esquema fieldNames é usado pelo modelo, árvore e DirectoryTree; A conversão de carga útil original não é necessária. O modelo funciona em SSR, não cria um DOM e não fornece scrollTo.
Esquema de dados e slots semânticos
Esquema digitado Passa os registros originais por treeData e fieldNames Nomeado key/title/children. String vazia em fieldNames Retorna o nome do campo padrão. TreeProps<Data>, TreeEventNode<Data> e TreeCheckInfo<Data> Salve o tipo de carga; TreeFieldDataNode<Payload, ChildFieldName> Descreve os dados recursivos. Os estados e canônicos key no nó de eventos se sobrepõem à carga útil dos mesmos campos e selectedNodes/checkedNodes contêm as entradas originais. Node.selected Reflete o estado antes da seleção, info.selected Relata o resultado da ação.
TreeTitleContent<Data> Suporta texto, números, matrizes aninhadas e trechos com o registro original. boolean, null e undefined não são exibidos; A falta title dá "---". Snippet no campo de cabeçalho é a prioridade titleRender. Para um objeto arbitrário no campo do título, defina titleRender: o objeto não se torna texto automaticamente.
Semantic slots definir classNames/styles para root, item, itemIcon, itemTitle e itemSwitcher. Registre o retorno de chamada com classes de retornos de propriedades ou strings CSS; O retorno de chamada deve calcular o design sem alterar o estado. ConfigProvider.tree estende-se à árvore e DirectoryTree mas não à árvore interna TreeSelect. As classes locais se acumulam com as comuns; CSS Vai no provedor do pedido styles, provedor style para root, local styles, normal style para root. class/style Os nós são salvos; Semantic style String vem depois de node.style.
aninhado ConfigProvider com tree=undefined herda a configuração; tree={} Substitui-o inteiramente. Alterar o design salva a seleção, o DOM e o download atual. O style usual permanece na raiz externa, não na lista interna.
Virtualização e rolagem
Árvore virtual Mostra 1000 arquivos na árvore e DirectoryTree com fieldNames. O DOM obtém a janela de string e selectedKeys permanece o estado de todo o modelo. Sem height ou em height=0 Todas as linhas abertas são exibidas sem limite de altura. virtual=undefined Herda ConfigProvider.virtual; Sem um valor comum, a árvore habilita a virtualização. virtual=false Salva todas as strings e rolagem nativa.
itemHeight Substitui a pontuação inicial de tokens de árvore; itemHeight=0 Desativa a janela. Após a montagem, as cordas reais são medidas com margens, as medidas são salvas por teclas para desmontar. SSR Usa a estimativa inicial sem medições do DOM, carregamento e temporizadores. loadData Para os ramos inicialmente abertos, ele começa quando atinge a janela montada.
scrollWidth Especifica a largura do conteúdo virtual. Roda, roda + roda, toque e tiras de arrasto funcionam em ambos os eixos, incluindo RTL. No exemplo, as coordenadas bidimensionais são mostradas no modo virtual. TreeRef.scrollTo pega um número ou {top,left} ou {key,align,offset} ou {index,align,offset}. align aceita top/bottom/auto. left - Posição lógica não negativa em RTL. offset - Número puro ou puro TreeScrollOffset função; getSize(startKey,endKey?) Retorna medido/valorizado top/bottom. Para o desconhecido endKey bottom=undefined; NaN/Infinity offset são substituídos por zero.
scrollTo Não seleciona um nó. Desconhecido key não muda de posição; null/undefined Mostrar barra de rolagem. Uma solicitação posterior cancela a anterior. itemScrollOffset Refere-se à rolagem automática do nó ativo; onScroll Obtém o evento Holder e bind:nativeElement continua sendo uma referência à raiz externa. Após a desmontagem, os links são limpos e os TreeRef salvos param de executar com segurança ações.
Mover para o nó aninhado usa createTree.getPath para procurar ancestrais. Atualizações do proprietário expandedKeys Aguarda o tick e as ligações scrollTo. autoExpand A solicitação de chave apenas adiciona a chave de destino no modo descontrolado, não abre ancestrais e não causa onExpand. Para controlled Atualização de madeira expandedKeys você mesmo.
Exemplos
Arraste o arquivo para outra linha ou entre as linhas. Manipulador onDrop Atualizações treeData; Bloqueado é proibido como alvo, a licença não pode ser arrastada.
Arrastando nós
Árvore e DirectoryTree: transferência de dados, allowDrop, alças próprias, RTL e janela virtual.
Drag.svelte<script lang="ts"> import { Button, Checkbox, ConfigProvider, DirectoryTree, Tree, type TreeDataNode, type TreeDropInfo, type TreeDropPosition, type TreeKey } from '@woodger/antd'; import { moveTreeNode } from './drop-tree'; function initial(): TreeDataNode[] { return [ { key: 'components', title: 'components', children: [ { key: 'button', title: 'Button.svelte', isLeaf: true }, { key: 'input', title: 'Input.svelte', isLeaf: true } ] }, { key: 'guides', title: 'guides', children: [{ key: 'start', title: 'start.md', isLeaf: true }] }, { key: 'locked', title: 'locked', disabled: true, children: [{ key: 'license', title: 'LICENSE', isLeaf: true }] } ]; } let data = $state<readonly TreeDataNode[]>(initial()); let expanded = $state<TreeKey[]>(['components', 'guides', 'locked']); let directory = $state(false); let rtl = $state(false); let virtual = $state(false); let inside = $state(true); let handle = $state(true); let lastDrop = $state('—'); const Component = $derived(directory ? DirectoryTree : Tree); function drop(info: TreeDropInfo) { const position = info.dropToGap ? info.dropPosition - Number(info.node.pos.split('-').at(-1)) : 0; data = moveTreeNode(data, info.dragNode.key, info.node.key, position as TreeDropPosition); lastDrop = `${info.dragNode.key} → ${info.node.key} (${position})`; } </script> {#snippet dragHandle()}<span aria-hidden="true">⠿</span>{/snippet} <div class="controls"> <Checkbox bind:checked={directory}>DirectoryTree</Checkbox> <Checkbox bind:checked={rtl}>RTL</Checkbox> <Checkbox bind:checked={virtual}>{("Janela virtual de arrastar e soltar")}</Checkbox> <Checkbox bind:checked={inside}>{("Permitir a transferência para o nó")}</Checkbox> <Checkbox bind:checked={handle}>{("Mostrar alça de arrastar")}</Checkbox> <Button onclick={() => { data = initial(); expanded = ['components', 'guides', 'locked']; lastDrop = '—'; }}>{("Redefinir a ordem da árvore")}</Button> </div> <ConfigProvider direction={rtl ? 'rtl' : 'ltr'}> <Component treeData={data} expandedKeys={expanded} onExpand={keys => { expanded = keys; }} blockNode draggable={{ icon: handle ? dragHandle : false, nodeDraggable: node => node.key !== 'license' }} allowDrop={({ dropNode, dropPosition }) => !dropNode.disabled && (inside || dropPosition !== 0)} onDrop={drop} height={virtual ? 160 : undefined} virtual={virtual} motion={false} aria-label={("Árvore arrastada")} /> </ConfigProvider> <output aria-label={("A última transferência da árvore")}>{lastDrop}</output> <p> {("Arraste o arquivo para outra linha ou entre as linhas. Manipulador onDrop Atualizações treeData; Bloqueado é proibido como alvo, a licença não pode ser arrastada.")} </p> <style>.controls { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; } output { display: block; margin-top: 12px; overflow-wrap: anywhere; } p { line-height: 1.6; }</style>drop-tree.tsimport type { TreeDataNode, TreeDropPosition, TreeKey } from '@woodger/antd'; export function moveTreeNode( data: readonly TreeDataNode[], dragKey: TreeKey, targetKey: TreeKey, position: TreeDropPosition ): readonly TreeDataNode[] { function find(nodes: readonly TreeDataNode[], key: TreeKey): TreeDataNode | undefined { for (const node of nodes) { if (node.key === key) { return node; } const nested = find(node.children ?? [], key); if (nested) { return nested; } } } const source = find(data, dragKey); if (!source || !find(data, targetKey) || find([source], targetKey) || ![-1, 0, 1].includes(position)) { return data; } function remove(nodes: readonly TreeDataNode[]): TreeDataNode[] { return nodes.filter(node => node.key !== dragKey).map( node => node.children ? { ...node, children: remove(node.children) } : node ); } function insert(nodes: readonly TreeDataNode[]): TreeDataNode[] { return nodes.flatMap(node => { if (node.key === targetKey) { if (position === 0) { return [{ ...node, isLeaf: false, children: [ ...(node.children ?? []), source! ] }]; } return position === -1 ? [source!, node] : [node, source!]; } return [ node.children ? { ...node, children: insert(node.children) } : node ]; }); } return insert(remove(data)); }
fases. Conjuntos de objetos próprios CSS fase e retornos de chamada; Motion=False desabilita a transição. A configuração de movimento reduzido é levada em consideração pela biblioteca.
Animação de abertura de árvore
Padrão collapse fases intrínsecas, tropeçando motion e salvando entradas adjacentes.
<script lang="ts">
import {
Button,
Checkbox,
DirectoryTree,
Input,
Tree,
type TreeKey,
type TreeMotionConfig
} from '@woodger/antd';
const data = [{
key: 'src', title: 'src', children: [
{ key: 'app', title: 'App.svelte', isLeaf: true },
{ key: 'layout', title: '+layout.svelte', isLeaf: true },
{ key: 'page', title: '+page.svelte', isLeaf: true }
]
}];
let expanded = $state<TreeKey[]>([]);
let directory = $state(false);
let enabled = $state(true);
let custom = $state(false);
let completed = $state(0);
let draft = $state('Svelte');
const Component = $derived(directory ? DirectoryTree : Tree);
const collapsed = () => `
height: 0px;
opacity: 0;
`;
const customMotion: TreeMotionConfig = {
motionName: 'site-tree-motion', motionDeadline: 500,
onAppearStart: collapsed,
onAppearActive: node => `
height: ${node.scrollHeight}px;
opacity: 1;
`,
onLeaveStart: node => `
height: ${node.offsetHeight}px;
opacity: 1;
`,
onLeaveActive: collapsed,
onAppearEnd: (_node, event) => {
if ('deadline' in event || 'propertyName' in event && event.propertyName === 'height') {
completed += 1;
return true;
} return false;
},
onLeaveEnd: (_node, event) => {
if ('deadline' in event || 'propertyName' in event && event.propertyName === 'height') {
completed += 1;
return true;
} return false;
}
};
</script>
<div class="controls">
<Checkbox bind:checked={directory}>DirectoryTree</Checkbox>
<Checkbox bind:checked={enabled}>{("Animação do galho de árvore")}</Checkbox>
<Checkbox bind:checked={custom}>{("Fases do próprio movimento")}</Checkbox>
<Button onclick={() => { expanded = expanded.includes('src') ? [] : ['src']; }}>
{("abrir ou recolher ramificação")}
</Button>
</div>
<Component treeData={data} expandedKeys={expanded} onExpand={keys => { expanded = keys; }}
motion={enabled ? custom ? customMotion : undefined : false} aria-label={("Árvore de animação")} />
<div
class="draft"
><Input
bind:value={draft}
aria-label={("Rascunho perto da árvore")}
/></div>
<output aria-label={("Árvore concluída")}>{completed}</output>
<p>
{("fases. Conjuntos de objetos próprios CSS fase e retornos de chamada; Motion=False desabilita a transição. A configuração de movimento reduzido é levada em consideração pela biblioteca.")}
</p>
<style>
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-bottom: 16px;
}
.draft {
max-width: 280px;
margin-block: 12px;
}
:global(.site-tree-motion-appear-active),
:global(.site-tree-motion-leave-active) {
overflow: hidden;
transition: height .22s ease, opacity .22s ease;
}
@media (prefers-reduced-motion: reduce) {
:global(.site-tree-motion-appear-active),
:global(.site-tree-motion-leave-active) {
transition: none;
}
}
p { line-height: 1.6; }
</style>
árvore comum
Teclas de início, disabled e checkable.
Basic.svelte<script lang="ts"> import { Tree } from '@woodger/antd'; import { treeData } from './data'; </script> <Tree {treeData} checkable defaultExpandedKeys={['project', 'docs']} defaultSelectedKeys={['button']} aria-label={("árvore comum")} />data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Projeto", children: [ { key: 'docs', title: "Documentação", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Exemplos", children: [{ key: 'forms', title: "Formulários", isLeaf: true }] }, { key: 'archive', title: "Arquivo", disabled: true, children: [{ key: 'archived', title: "Documento", isLeaf: true }] } ] }];
Árvore gerenciada
Independente expandedKeys e selectedKeys.
Controlled.svelte<script lang="ts"> import { Button, Tree, type TreeKey } from '@woodger/antd'; import { treeData } from './data'; let expanded = $state<TreeKey[]>(['project', 'docs']); let selected = $state<TreeKey[]>(['button']); </script> <style> .example { display: grid; gap: 20px; } </style> <div class="example"> <Tree {treeData} multiple expandedKeys={expanded} selectedKeys={selected} onExpand={keys => { expanded = keys; }} onSelect={keys => { selected = keys; }} aria-label={("Árvore gerenciada")} /> <Button onclick={() => { expanded = ['project']; selected = []; }}> {("Redefinir a árvore gerenciada")} </Button> <output aria-label={("Seleção de uma árvore controlada")} >{("Selecionado: ")}{(selected.map(String).join(', ') || '—')}</output> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Projeto", children: [ { key: 'docs', title: "Documentação", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Exemplos", children: [{ key: 'forms', title: "Formulários", isLeaf: true }] }, { key: 'archive', title: "Arquivo", disabled: true, children: [{ key: 'archived', title: "Documento", isLeaf: true }] } ] }];
Marcas relacionadas e independentes
Condução, status parcial e checkStrictly.
Checks.svelte<script lang="ts"> import { Checkbox, Tree, type TreeKey, type TreeCheckedKeys } from '@woodger/antd'; import { treeData } from './data'; let strict = $state(false); let checked = $state<TreeKey[] | TreeCheckedKeys>([]); let keys = $derived('checked' in checked ? checked.checked : checked); </script> <style> .example { display: grid; gap: 20px; } </style> <div class="example"> <Checkbox checked={strict} onCheckedChange={next => { strict = next; checked = []; }}> {("Árvore independente")} </Checkbox> <Tree {treeData} checkable checkStrictly={strict} checkedKeys={checked} onCheck={next => { checked = next; }} defaultExpandAll aria-label={("Árvore de marcação")} /> <output aria-label={("Chaves de árvore marcadas")}>{("Marcado: ")}{(keys .map(String).join(', ') || '—')}</output> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Projeto", children: [ { key: 'docs', title: "Documentação", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Exemplos", children: [{ key: 'forms', title: "Formulários", isLeaf: true }] }, { key: 'archive', title: "Arquivo", disabled: true, children: [{ key: 'archived', title: "Documento", isLeaf: true }] } ] }];
Baixe com erro e repita
Promise loadData, loadedKeys e folga quando reiniciado.
Async.svelte<script lang="ts"> import { Button } from '@woodger/antd'; import LazyTree from './LazyTree.svelte'; let revision = $state(0); </script> <style> .example { display: grid; gap: 20px; } </style> <div class="example"> <Button onclick={() => { revision++; }}> {("Redefinir o carregamento da árvore")} </Button> {#key revision}<LazyTree />{/key} </div>LazyTree.svelte<script lang="ts"> import { onDestroy } from 'svelte'; import { Alert, Checkbox, Tree, type TreeDataNode, type TreeKey, type TreeEventNode } from '@woodger/antd'; let nodes = $state.raw<TreeDataNode[]>([{ key: 'remote', title: "Partições remotas", isLeaf: false }]); let loaded = $state<TreeKey[]>([]); let fail = $state(false); let busy = $state(false); let error = $state(''); let active = true; let timer: ReturnType<typeof setTimeout> | undefined; let settle: (() => void) | undefined; function loadData(node: TreeEventNode): Promise<void> { const failed = fail; busy = true; error = ''; return new Promise((resolve, reject) => { settle = resolve; timer = setTimeout(() => { timer = undefined; settle = undefined; if (!active) { resolve(); return; } busy = false; if (failed) { error = ("Não é possível carregar as seções. Desmarque a caixa de erro e abra a ramificação novamente."); reject(new Error((error))); } else { nodes = nodes.map( item => item.key === node.key ? { ...item, children: [ { key: 'remote-form', title: "Formulários no servidor", isLeaf: true }, { key: 'remote-table', title: "Tabelas no servidor", isLeaf: true } ] } : item ); resolve(); } }, 400); }); } onDestroy(() => { active = false; clearTimeout(timer); settle?.(); }); </script> <style> .example { display: grid; gap: 20px; } </style> <div class="example"> <Checkbox bind:checked={fail} disabled={busy}> {("Carregando erro Árvore")} </Checkbox> <Tree treeData={nodes} {loadData} loadedKeys={loaded} onLoad={keys => { if (active) loaded = keys; }} aria-label={("Carregando")} /> {#if error}<Alert type="error" title={("Erro de carregamento da árvore")} description={error} showIcon />{/if} <output aria-label={("Chaves de árvore carregadas")} >{("Baixado: ")}{(loaded.map(String).join(', ') || '—')}</output> </div>
Pesquisa e luz de fundo
A pesquisa revela os pais; filterTreeNode Destaca as correspondências.
Search.svelte<script lang="ts"> import { Input, Tree, type TreeDataNode, type TreeKey } from '@woodger/antd'; import { treeData } from './data'; let query = $state(''); let expanded = $state<TreeKey[]>(['project']); function search(value: string | undefined) { query = value ?? ''; const found = new Set<TreeKey>(); function visit(nodes: readonly TreeDataNode[], ancestors: TreeKey[]) { for (const node of nodes) { if (query && String(node.title).toLocaleLowerCase().includes(query.toLocaleLowerCase())) { for (const key of ancestors) found.add(key); } if (node.children) visit(node.children, [...ancestors, node.key]); } } visit(treeData, []); expanded = query ? [...found] : ['project']; } </script> <style> .example { display: grid; gap: 20px; } mark { color: var(--ant-color-text); background: var(--ant-color-warning-bg); } </style> {#snippet title(node: TreeDataNode)} {@const text = String(node.title ?? node.key)} {@const index = query ? text.toLocaleLowerCase().indexOf(query.toLocaleLowerCase()) : -1} {#if index < 0} {(text)} {:else}{(text.slice(0, index))}<mark> {(text.slice(index, index + query.length))} </mark>{(text.slice(index + query.length))}{/if} {/snippet} <div class="example" ><Input aria-label={("Pesquisar árvore da seção")} value={query} onValueChange={search} allowClear /> <Tree {treeData} expandedKeys={expanded} onExpand={keys => { expanded = keys; }} titleRender={title} filterTreeNode={node => Boolean(query && String(node.title).toLocaleLowerCase().includes( query.toLocaleLowerCase() ))} aria-label={("Pesquisar na árvore")} /></div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Projeto", children: [ { key: 'docs', title: "Documentação", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Exemplos", children: [{ key: 'forms', title: "Formulários", isLeaf: true }] }, { key: 'archive', title: "Arquivo", disabled: true, children: [{ key: 'archived', title: "Documento", isLeaf: true }] } ] }];
Linhas de conexão
Linhas e ícones de folhas.
Lines.svelte<script lang="ts"> import { Checkbox, Tree } from '@woodger/antd'; import { treeData } from './data'; let line = $state(true); let leafIcon = $state(true); </script> <style> .example { display: grid; gap: 20px; } .settings { display: flex; flex-wrap: wrap; gap: 16px; } </style> <div class="example"> <div class="settings"> <Checkbox bind:checked={line}> {("Linha das árvores")} </Checkbox> <Checkbox bind:checked={leafIcon}>{("Ícones de folha de árvore")}</Checkbox> </div> <Tree {treeData} showLine={line ? { showLeafIcon: leafIcon } : false} defaultExpandAll aria-label={("Árvore com linhas")} /> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Projeto", children: [ { key: 'docs', title: "Documentação", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Exemplos", children: [{ key: 'forms', title: "Formulários", isLeaf: true }] }, { key: 'archive', title: "Arquivo", disabled: true, children: [{ key: 'archived', title: "Documento", isLeaf: true }] } ] }];
Seus emblemas e design
ícone/switcherIcon trechos, class/style root.
Icons.svelte<script lang="ts"> import { Tree, type TreeEventNode } from '@woodger/antd'; import { treeData } from './data'; </script> {#snippet icon(node: TreeEventNode)}<span aria-hidden="true">{(node.isLeaf ? '▤' : node.expanded ? '▣' : '□')}</span>{/snippet} {#snippet switcher(node: TreeEventNode)}<span aria-hidden="true">{(node.expanded ? '−' : '+')}</span>{/snippet} <Tree {treeData} showIcon {icon} switcherIcon={switcher} defaultExpandAll aria-label={("ícones de sua árvore")} class="tree-custom-root" style=" padding: 12px; border: 1px dashed var(--ant-color-border); border-radius: 8px; " />data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Projeto", children: [ { key: 'docs', title: "Documentação", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Exemplos", children: [{ key: 'forms', title: "Formulários", isLeaf: true }] }, { key: 'archive', title: "Arquivo", disabled: true, children: [{ key: 'archived', title: "Documento", isLeaf: true }] } ] }];
Área de texto
All String Width
Largura da string e rolagem
blockNode e regular scroll Recipiente com height.
Block.svelte<script lang="ts"> import { Tree } from '@woodger/antd'; import { treeData } from './data'; </script> <style> .examples { display: grid; gap: 24px; } h4 { margin: 0 0 12px; } </style> <div class="examples">{#each [false, true] as block (String(block))}<div> <h4>{(block ? "All String Width" : "Área de texto")}</h4> <Tree {treeData} blockNode={block} height={160} virtual={false} defaultExpandAll aria-label={(block ? "Árvore de bloco" : "Largura normal da árvore")} /> </div>{/each}</div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Projeto", children: [ { key: 'docs', title: "Documentação", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Exemplos", children: [{ key: 'forms', title: "Formulários", isLeaf: true }] }, { key: 'archive', title: "Arquivo", disabled: true, children: [{ key: 'archived', title: "Documento", isLeaf: true }] } ] }];
Teclado e Foco
O método focus, a propriedade tabIndex e os eventos de teclado.
Keyboard.svelte<script lang="ts"> import { Button, Tree, type TreeKey, type TreeRef } from '@woodger/antd'; import { treeData } from './data'; let tree = $state<TreeRef>(); let active = $state<TreeKey | null>(null); let lastEvent = $state('—'); </script> <style> .example { display: grid; gap: 20px; } </style> <div class="example"> <Button disabled={!tree} onclick={() => tree?.focus()}> {("Passe o foco para a árvore")} </Button> <Tree {treeData} bind:this={tree} defaultExpandedKeys={['project']} tabIndex={-1} onActiveChange={key => { active = key; }} onFocus={() => { lastEvent = 'onFocus'; }} onBlur={() => { lastEvent = 'onBlur'; }} onKeyDown={event => { lastEvent = `onKeyDown ${event.key}`; }} aria-label={("Teclado")} /> <output aria-label={("Árvore de nós ativos")}>{("Ativo: ")}{(active === null ? '—' : String(active))}</output> <output aria-label={("Último evento")}>{lastEvent}</output> </div>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Projeto", children: [ { key: 'docs', title: "Documentação", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Exemplos", children: [{ key: 'forms', title: "Formulários", isLeaf: true }] }, { key: 'archive', title: "Arquivo", disabled: true, children: [{ key: 'archived', title: "Documento", isLeaf: true }] } ] }];
Tema do componente
Dimensões reativas de strings, recuos e cores; A escolha é salva quando o tema é alterado.
Theme.svelte<script lang="ts"> import { Checkbox, ConfigProvider, Tree } from '@woodger/antd'; import type { TreeKey } from '@woodger/antd'; import { treeData } from './data'; let enabled = $state(true); let selected = $state<TreeKey[]>(['button']); const tokens = { titleHeight: 40, switcherSize: 36, indentSize: 32, nodeSelectedBg: '#fff1b8', nodeSelectedColor: '#874d00' }; </script> <style> .settings { margin-bottom: 24px; } </style> <div class="settings"> <Checkbox bind:checked={enabled}>{("Aplicar tokens de árvore")}</Checkbox> </div> <ConfigProvider direction="rtl" theme={{ components: { Tree: enabled ? tokens : {} } }}> <Tree {treeData} defaultExpandAll selectedKeys={selected} aria-label={("Tema da árvore")} onSelect={keys => { selected = [...keys]; }} /> </ConfigProvider>data.tsimport type { TreeDataNode } from '@woodger/antd'; export const treeData: TreeDataNode[] = [{ key: 'project', title: "Projeto", children: [ { key: 'docs', title: "Documentação", children: [ { key: 'button', title: 'Button', isLeaf: true }, { key: 'input', title: 'Input', isLeaf: true } ] }, { key: 'examples', title: "Exemplos", children: [{ key: 'forms', title: "Formulários", isLeaf: true }] }, { key: 'archive', title: "Arquivo", disabled: true, children: [{ key: 'archived', title: "Documento", isLeaf: true }] } ] }];
Selecionar uma string e marcações são independentes. A ramificação "Exemplos" é carregada ao abrir.
Seções de documentação
Exemplo original com seleção, marcas, download e redefinição.
<script lang="ts">
import {
Tree,
Button,
type TreeDataNode,
type TreeKey,
type TreeCheckedKeys
} from '@woodger/antd';
const initial: TreeDataNode[] = [
{
key: 'docs',
title: "Documentação",
children: [
{ key: 'start', title: "Primeiros passos", isLeaf: true },
{
key: 'components',
title: "Componentes",
children: [
{ key: 'button', title: 'Button', isLeaf: true },
{ key: 'input', title: 'Input', isLeaf: true }
]
}
]
},
{ key: 'examples', title: "Exemplos", isLeaf: false }
];
let nodes = $state.raw(initial);
let expanded = $state<TreeKey[]>(['docs']);
let selected = $state<TreeKey[]>([]);
let checked = $state<TreeKey[] | TreeCheckedKeys>([]);
let loaded = $state<TreeKey[]>([]);
let result = $state('');
let generation = 0;
async function load(node: { key: TreeKey }) {
const version = generation;
await Promise.resolve();
if (version !== generation) {
return;
}
nodes = nodes.map(
item =>
item.key === node.key
? {
...item,
children: [
{ key: 'form-demo', title: "formulário", isLeaf: true },
{ key: 'table-demo', title: "Tabela", isLeaf: true }
]
}
: item
);
}
</script>
<style>
output {
display: block;
margin-top: 16px;
}
</style>
<div style="max-width:640px">
<Tree
aria-label={("Árvore de seções")}
treeData={nodes}
checkable
showLine
blockNode
expandedKeys={expanded}
selectedKeys={selected}
checkedKeys={checked}
loadedKeys={loaded}
onLoad={keys => { loaded = keys; }}
loadData={load}
onExpand={keys => { expanded = keys; }}
onSelect={(keys, info) => {
selected = keys;
result = info.selectedNodes.map(
node => typeof node.title === 'string' ? node.title : String(node.key)
)
.join(', ');
}}
onCheck={keys => { checked = keys; }}
/>
<p>
{("Selecionar uma string e marcações são independentes. A ramificação \"Exemplos\" é carregada ao abrir.")}
</p>
<Button
onclick={() => {
generation++;
nodes = initial;
expanded = ['docs'];
selected = [];
checked = [];
loaded = [];
result = '';
}}
>{("Reiniciar árvore")}</Button>
<output aria-label={("Seção selecionada")}>{result}</output>
</div>
nós, switcher, caixa de seleção e linhas, use o prefixo da árvore. DOM, IDS ARIA, chaves selecionadas e download inacabado são salvos. TreeSelect Possui seu próprio adaptador de árvore.
CSS Árvore de prefixo
namespace geral ConfigProvider e local prefixCls; O estado do componente é salvo ao alterar o nome.
<script lang="ts">
import { Checkbox, ConfigProvider, Tree, type TreeKey } from '@woodger/antd';
let custom = $state(true);
let local = $state(true);
const prefix = $derived(custom ? 'suite' : 'ant');
const localPrefix = $derived(local ? 'project-tree' : '');
let checkedKeys = $state<readonly TreeKey[]>(['docs']);
</script>
<style>
.example,
.prefix-stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 16px;
min-width: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
p { margin: 0; }
output { overflow-wrap: anywhere; }
</style>
<div class="example">
<div class="controls">
<Checkbox bind:checked={custom}>{("General Prefix Tree Suite")}</Checkbox>
<Checkbox bind:checked={local}>{("Árvore de prefixo local")}</Checkbox>
</div>
<ConfigProvider prefixCls={prefix} theme={{ cssVar: { prefix: 'tree-theme' } }}>
<div class="prefix-stage">
<Tree prefixCls={localPrefix} checkable showLine defaultExpandAll checkedKeys={checkedKeys}
onCheck={keys => checkedKeys = Array.isArray(keys) ? keys : keys.checked}
aria-label={("Árvore com prefixo")} treeData={[
{
key: 'project', title: "Projeto", children: [
{ key: 'docs', title: "Documentação" }, { key: 'examples', title: "Exemplos" }
]
}
]} />
<output
aria-label={("Marcas com prefixo")}
>{checkedKeys.join(', ')}</output>
</div>
</ConfigProvider>
<output aria-label={("CSS-prefix tree")}>{("Geral: ")}{prefix}{("; Local: ")}{(localPrefix
|| ("Do provedor"))}</output>
<p>
{("nós, switcher, caixa de seleção e linhas, use o prefixo da árvore. DOM, IDS ARIA, chaves selecionadas e download inacabado são salvos. TreeSelect Possui seu próprio adaptador de árvore.")}
</p>
</div>
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 com cabeçalho
click, doubleClick e desativar a abertura; A seleção e a divulgação são controladas separadamente.
<script lang="ts">
import { Flex, Tree, type TreeExpandAction, type TreeKey } from '@woodger/antd';
let action = $state<TreeExpandAction>('click');
let expanded = $state<TreeKey[]>([]);
let selected = $state<TreeKey[]>([]);
const data = [{
key: 'src', title: 'src', children: [{
key: 'app',
title: 'App.svelte',
isLeaf: true
}]
}];
</script>
<Flex vertical gap="medium">
<label>expandAction <select value={String(action)} onchange={event => {
action = event.currentTarget.value === 'false'
? false
: event.currentTarget.value as TreeExpandAction;
expanded = [];
}}>
<option
value="false"
>false</option><option
value="click"
>click</option><option
value="doubleClick"
>doubleClick</option>
</select></label>
<Tree treeData={data} expandAction={action} expandedKeys={expanded} selectedKeys={selected}
onExpand={keys => { expanded = keys; }} onSelect={keys => { selected = keys; }}
aria-label={("Divulgação com cabeçalho")} />
<Flex gap="small" wrap>
<output aria-label="expandedKeys">{expanded.join(', ') || '—'}</output>
<output aria-label="selectedKeys">{selected.join(', ') || '—'}</output>
</Flex>
</Flex>
<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>
Normal Click seleciona um arquivo, seleção de switches Ctrl/Meta, Shift aloca um intervalo visível. Clique novamente em salvar a escolha.
Árvore de arquivos
DirectoryTree, seleção Ctrl/Meta e intervalo de turno.
<script lang="ts">
import { DirectoryTree, type TreeKey } from '@woodger/antd';
let selected = $state<TreeKey[]>([]);
const data = [{
key: 'src', title: 'src', children: [
{ key: 'app', title: 'App.svelte', isLeaf: true },
{
key: 'routes', title: 'routes', children: [{
key: 'page',
title: '+page.svelte',
isLeaf: true
}]
},
{ key: 'styles', title: 'styles.css', isLeaf: true }
]
}];
</script>
<style>
output {
display: block;
margin-block-start: 12px;
}
</style>
<DirectoryTree treeData={data} multiple defaultExpandAll selectedKeys={selected}
onSelect={keys => { selected = keys; }} aria-label={("Árvore de arquivos")} />
<output aria-label={("Selecionando arquivos")}>{selected.join(', ') || '—'}</output>
<p>
{("Normal Click seleciona um arquivo, seleção de switches Ctrl/Meta, Shift aloca um intervalo visível. Clique novamente em salvar a escolha.")}
</p>
O próprio nó switcherIcon tem precedência sobre o ícone compartilhado e o download. Os retornos de chamada de foco também são chamados para nós desabilitados.
Ícones de nó e retornos de chamada de foco
switcherIcon, showLeafIcon Snippet e apontando para o nó disabled.
<script lang="ts">
import { Tree, type TreeDataNode, type TreeEventNode } from '@woodger/antd';
let hovered = $state('—');
let data = $derived<TreeDataNode[]>([{
key: 'src', title: 'src', switcherIcon: branch,
children: [{ key: 'app', title: 'App.svelte', isLeaf: true }, {
key: 'config',
title: 'config.ts',
isLeaf: true,
disabled: true
}]
}]);
</script>
<style>
output {
display: block;
margin-block-start: 12px;
}
</style>
{#snippet branch(node: TreeEventNode)}<span
aria-hidden="true"
>{node.expanded ? '−' : '+'}</span>{/snippet}
{#snippet leaf(node: TreeEventNode)}<span
aria-hidden="true"
>{node.disabled ? '◇' : '◆'}</span>{/snippet}
<Tree treeData={data} defaultExpandAll switcherIcon={leaf} showLine={{ showLeafIcon: leaf }}
onMouseEnter={({ node }) => { hovered = String(node.key); }} onMouseLeave={() => {
hovered = '—';
}}
aria-label={("ícones de árvore e apontando")} />
<output aria-label={("Nó sob o ponteiro")}>{hovered}</output>
<p>
{("O próprio nó switcherIcon tem precedência sobre o ícone compartilhado e o download. Os retornos de chamada de foco também são chamados para nós desabilitados.")}
</p>
createTree Lê os dados atuais e fieldNames via Getters. Substitua links para atualizar; A chave desconhecida retorna um caminho vazio. O modelo não rola o DOM.
Caminho de acordo com a árvore
createTree/getPath, novos dados e mudança fieldNames sem DOM ref.
<script lang="ts">
import { Button, Flex, Tree, createTree, type TreeFieldNames } from '@woodger/antd';
type Entry = { id: string; caption: string; nodes?: Entry[] };
let moved = $state(false);
let data = $derived<Entry[]>([{
id: moved ? 'archive' : 'src',
caption: moved ? 'archive' : 'src',
nodes: [{ id: 'app', caption: 'App.svelte' }]
}]);
let fields = $state<TreeFieldNames>({ key: 'id', title: 'caption', children: 'nodes' });
const model = createTree(() => data, { get fieldNames() { return fields; } });
const getPath = model.getPath;
let path = $derived(getPath('app'));
</script>
<Flex vertical gap="medium">
<Tree
treeData={data}
fieldNames={fields}
expandedKeys={data.map(node => node.id)}
aria-label={("Dados do caminho da árvore")}
/>
<Flex gap="small" wrap>
<Button onclick={() => { moved = !moved; }}>{("Mover o nó")}</Button>
<Button onclick={() => {
fields = fields.key === 'id' ? {
key: 'caption',
title: 'caption',
children: 'nodes'
} : { key: 'id', title: 'caption', children: 'nodes' };
}}>{("Alterar o campo-chave")}</Button>
</Flex>
<output aria-label="getPath">{path.map(entity => String(entity.key)).join(' / ') || '—'}</output>
</Flex>
<p>
{("createTree Lê os dados atuais e fieldNames via Getters. Substitua links para atualizar; A chave desconhecida retorna um caminho vazio. O modelo não rola o DOM.")}
</p>
fieldNames Define id/legenda/nós sem conversão de dados. TreeEventNode Contém chave e status canônicos; selectedNodes Salva as entradas originais e sua carga útil.
Typized Tree Schema
Árvore e DirectoryTree com fieldNames, carga útil e estados canônicos.
<script lang="ts">
import {
Checkbox,
DirectoryTree,
Tree,
type TreeEventNode,
type TreeFieldDataNode,
type TreeProps
} from '@woodger/antd';
type Entry = TreeFieldDataNode<{
id: number;
key: 'payload-key';
selected: 'payload-selected';
caption: { label: string };
rank: number;
}, 'nodes'>;
const leaf: Entry = {
id: 0, key: 'payload-key', selected: 'payload-selected', caption: {
label: 'App.svelte'
}, rank: 7
};
const data: Entry[] = [{
id: 1, key: 'payload-key', selected: 'payload-selected', caption: {
label: 'src'
}, rank: 3, nodes: [leaf]
}];
const fields = { key: 'id', title: 'caption', children: 'nodes' };
let directory = $state(false);
let result = $state('—');
const record: NonNullable<TreeProps<Entry>['onSelect']> = (_keys, info) => {
result = JSON.stringify({
key: info.node.key,
selected: info.selected,
nodeSelected: info.node.selected,
rank: info.node.rank,
rawKey: info.selectedNodes[0]?.key,
rawSelected: info.selectedNodes[0]?.selected,
original: info.selectedNodes[0] === leaf
});
};
</script>
{#snippet title(node: Entry)}{node.caption.label}{/snippet}
{#snippet icon(node: TreeEventNode<Entry>)}<span aria-hidden="true">{node.rank}</span>{/snippet}
<div class="settings"><Checkbox bind:checked={directory}>DirectoryTree</Checkbox></div>
{#if directory}
<DirectoryTree treeData={data} fieldNames={fields} titleRender={title} {icon} defaultExpandAll
onSelect={record} aria-label={("Árvore com dados tipados")} />
{:else}
<Tree treeData={data} fieldNames={fields} titleRender={title} {icon} showIcon defaultExpandAll
onSelect={record} aria-label={("Árvore com dados tipados")} />
{/if}
<output aria-label={("Dados do evento em árvore")}>{result}</output>
<p>
{("fieldNames Define id/legenda/nós sem conversão de dados. TreeEventNode Contém chave e status canônicos; selectedNodes Salva as entradas originais e sua carga útil.")}
</p>
<style>
.settings { margin-block-end: 12px; }
output {
display: block;
margin-block-start: 12px;
overflow-wrap: anywhere;
}
</style>
root, item, itemIcon, itemTitle e itemSwitcher tome classes e CSS strings. Os valores locais são complementados pelo provedor; A árvore aninhada={} substitui a configuração geral. O design muda sem uma escolha.
Semantic slots Tree
ConfigProvider.tree, design de callbacks locais, configuração aninhada e composto title.
<script lang="ts">
import {
Button,
Checkbox,
ConfigProvider,
DirectoryTree,
Tree,
type TreeConfig,
type TreeDataNode,
type TreeKey,
type TreeProps
} from '@woodger/antd';
let local = $state(true);
let reset = $state(false);
let directory = $state(false);
let alternate = $state(false);
let selected = $state<TreeKey[]>([]);
const data: TreeDataNode[] = [{
key: 'src',
class: 'payload-node',
style: 'font-size:19px',
title: ['src', null, [false, ' / ', suffix]],
children: [{ key: 'app', title: 'App.svelte', isLeaf: true }]
}];
const provider: TreeConfig = {
class: 'tree-provider', style: 'padding:10px',
classNames: {
root: 'provider-root',
item: 'provider-item',
itemIcon: 'provider-icon',
itemTitle: 'provider-title',
itemSwitcher: 'provider-switcher'
},
styles: {
item: 'font-size:15px',
itemTitle: 'letter-spacing:1px',
itemIcon: 'color:rgb(30,90,130)'
}
};
let appearance = $derived<TreeProps['styles']>(({ props }) => ({
root: `border:1px solid ${alternate ? 'rgb(130,90,30)' : 'rgb(30,90,130)'}`,
item: 'font-size:17px',
itemTitle: `letter-spacing:${alternate ? 3 : 2}px`,
itemSwitcher: `opacity:${props.disabled ? 0.5 : 1}`
}));
const classes: TreeProps['classNames'] = ({ props }) => ({
root: props.showIcon ? 'local-icons' : 'local-root',
itemTitle: 'local-title'
});
const select: NonNullable<TreeProps['onSelect']> = keys => { selected = keys; };
</script>
{#snippet suffix(_node: TreeDataNode)}<strong>files</strong>{/snippet}
<div class="controls">
<Checkbox bind:checked={local}>{("design local da árvore")}</Checkbox>
<Checkbox bind:checked={reset}>{("Configuração vazia do provedor")}</Checkbox>
<Checkbox bind:checked={directory}>DirectoryTree</Checkbox>
<Button
onclick={() => { alternate = !alternate; }}
>{("Mude o design da árvore")}</Button>
</div>
<ConfigProvider tree={provider}>
<ConfigProvider tree={reset ? {} : undefined}>
{#if directory}
<DirectoryTree treeData={data} defaultExpandAll selectedKeys={selected} onSelect={select}
classNames={local ? classes : undefined} styles={local ? appearance : undefined}
aria-label={("Árvore com slots semânticos")} />
{:else}
<Tree treeData={data} showIcon defaultExpandAll selectedKeys={selected} onSelect={select}
classNames={local ? classes : undefined} styles={local ? appearance : undefined}
aria-label={("Árvore com slots semânticos")} />
{/if}
</ConfigProvider>
</ConfigProvider>
<output
aria-label={("Escolha de madeira com decoração")}
>{selected.join(', ') || '—'}</output>
<p>
{("root, item, itemIcon, itemTitle e itemSwitcher tome classes e CSS strings. Os valores locais são complementados pelo provedor; A árvore aninhada={} substitui a configuração geral. O design muda sem uma escolha.")}
</p>
<style>.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
} output {
display: block;
margin-block-start: 12px;
}</style>
no modelo de arquivo 1000; A janela virtual monta apenas as strings necessárias. As teclas de seleção são salvas fora da janela. Virtual=Undefined Herda o provedor, virtual=false gera todas as strings com rolagem nativa.
Árvore de virtualização e DirectoryTree
1000 arquivos, ambos os eixos, RTL, strings medidas, configurações virtual e ciclo de vida TreeRef.
<script lang="ts">
import { Button, Checkbox, ConfigProvider, DirectoryTree, InputNumber, Tree,
type TreeKey, type TreeRef, type TreeScrollAlign, type TreeScrollOffset } from '@woodger/antd';
let directory = $state(false);
let rtl = $state(false);
let providerVirtual = $state(true);
let localOff = $state(false);
let variable = $state(false);
let measuredOffset = $state(false);
let mounted = $state(true);
let target = $state<number | null>(900);
let align = $state<TreeScrollAlign>('top');
let tree = $state<TreeRef>();
let saved = $state<TreeRef>();
let element = $state<HTMLDivElement>();
let selected = $state<TreeKey[]>([]);
let top = $state(0);
const fields = { key: 'id', title: 'caption' };
let data = $derived(Array.from({ length: 1000 }, (_, id) => ({ id,
caption: `file-${id}.ts — src/components/long-directory-name/component-${id}.svelte`,
isLeaf: true, style: `
min-width: 900px;
min-height: ${variable ? id % 3 ? 40 : 64 : 28}px;
`
})));
const rowOffset: TreeScrollOffset = ({ getSize }) => {
const size = getSize(0);
return (size.bottom ?? size.top) - size.top;
};
let Component = $derived(directory ? DirectoryTree : Tree);
</script>
<div class="controls">
<Checkbox bind:checked={directory}>DirectoryTree</Checkbox>
<Checkbox bind:checked={rtl}>RTL</Checkbox>
<Checkbox bind:checked={providerVirtual}>{("Virtualização de provedor")}</Checkbox>
<Checkbox bind:checked={localOff}>{("localmente virtual=falso")}</Checkbox>
<Checkbox bind:checked={variable}>{("Altura diferente da linha")}</Checkbox>
<Checkbox
bind:checked={measuredOffset}
>{("Altura da primeira linha")}</Checkbox>
<Checkbox bind:checked={mounted}>{("Mostrar árvore virtual")}</Checkbox>
</div>
<div class="controls">
<InputNumber
aria-label={("Índice de chave ou linha")}
bind:value={target}
min={0}
max={999}
precision={0}
style="width:100px"
/>
<label>align <select
bind:value={align}
><option
value="top"
>top</option><option
value="bottom"
>bottom</option><option
value="auto"
>auto</option></select></label>
<Button disabled={!tree} onclick={() => tree?.scrollTo({
key: target ?? 0,
align,
offset: measuredOffset ? rowOffset : 0
})}>scrollTo(key)</Button>
<Button
disabled={!tree}
onclick={() => tree?.scrollTo({ index: target ?? 0, align })}
>scrollTo(index)</Button>
<Button disabled={!tree || !providerVirtual || localOff} onclick={() => tree?.scrollTo({
top: 120,
left: 160
})}>scrollTo(top, left)</Button>
<Button disabled={!tree} onclick={() => tree?.scrollTo({ top: 0, left: 0 })}>
{("Para o início da árvore")}
</Button>
<Button disabled={!tree} onclick={() => tree?.focus()}>focus()</Button>
<Button disabled={!tree} onclick={() => tree?.blur()}>blur()</Button>
<Button disabled={!tree} onclick={() => tree?.scrollTo(null)}>scrollTo(null)</Button>
<Button
disabled={!tree}
onclick={() => { saved = tree; }}
>{("Salvar TreeRef")}</Button>
<Button
disabled={!saved}
onclick={() => { saved?.scrollTo(0); saved?.focus(); saved?.blur(); }}
>{("Chamada salva TreeRef")}</Button>
</div>
<ConfigProvider virtual={providerVirtual} direction={rtl ? 'rtl' : 'ltr'}>
<div class="viewport">
{#if mounted}
<Component treeData={data} fieldNames={fields} height={210} itemHeight={32} scrollWidth={1200}
virtual={localOff ? false : undefined} itemScrollOffset={8}
selectedKeys={selected} onSelect={keys => { selected = keys; }}
onScroll={event => { top = event.currentTarget.scrollTop; }}
bind:this={tree} bind:nativeElement={element} aria-label={("Árvore de arquivos virtuais")} />
{/if}
</div>
</ConfigProvider>
<output
aria-label={("Seleção de árvore virtual")}
>{selected.join(', ') || '—'}</output>
<output aria-label="TreeRef nativeElement">{element?.tagName ?? '—'}</output>
<output aria-label="Tree onScroll">{Math.round(top)}</output>
<p>
{("no modelo de arquivo 1000; A janela virtual monta apenas as strings necessárias. As teclas de seleção são salvas fora da janela. Virtual=Undefined Herda o provedor, virtual=false gera todas as strings com rolagem nativa.")}
</p>
<style>
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.viewport { min-width:0; }
output {
display: block;
margin-block-start: 8px;
overflow-wrap: anywhere;
}
</style>
createTree Encontra os ancestrais, o proprietário atualiza expandedKeys, depois que o tick é chamado TreeRef.scrollTo. AutoExpand apenas adiciona a chave de destino no modo descontrolado e não revela automaticamente todos os ancestrais.
Role até o nó aninhado
createTree/getPath Encontra os ancestrais, o proprietário abre o caminho para TreeRef.scrollTo.
<script lang="ts">
import { tick } from 'svelte';
import {
Button,
Input,
Tree,
createTree,
type TreeDataNode,
type TreeKey,
type TreeRef
} from '@woodger/antd';
const data: TreeDataNode[] = [{
key: 'project', title: 'project', children:
Array.from({ length: 20 }, (_, folder) => ({
key: `folder-${folder}`,
title: `folder-${folder}`,
children:
Array.from({ length: 50 }, (_, file) => ({
key: `file-${folder}-${file}`,
title: `file-${folder}-${file}.svelte`,
isLeaf: true
}))
}))
}];
const model = createTree(data);
let target = $state('file-19-49');
let expanded = $state<TreeKey[]>([]);
let tree = $state<TreeRef>();
async function reveal() {
const path = model.getPath(target);
if (!path.length) {
return;
}
expanded = [...new Set([...expanded, ...path.slice(0, -1).map(entity => entity.key)])];
await tick();
tree?.scrollTo({ key: target, align: 'top' });
}
async function reset() {
expanded = [];
await tick();
tree?.scrollTo(0);
}
</script>
<div class="controls">
<Input
aria-label={("Chave de nó aninhada")}
bind:value={target}
style="width:180px"
/>
<Button disabled={!tree} onclick={reveal}>{("Expanda caminho e role")}</Button>
<Button disabled={!tree} onclick={reset}>{("Árvore de recolhimento")}</Button>
</div>
<Tree treeData={data} height={210} expandedKeys={expanded} onExpand={keys => { expanded = keys; }}
bind:this={tree} aria-label={("Role até o nó aninhado")} />
<output aria-label={("Caminho de rolagem")}>{model.getPath(target).map(entity => String(
entity.key
)).join(' / ') || '—'}</output>
<p>
{("createTree Encontra os ancestrais, o proprietário atualiza expandedKeys, depois que o tick é chamado TreeRef.scrollTo. AutoExpand apenas adiciona a chave de destino no modo descontrolado e não revela automaticamente todos os ancestrais.")}
</p>
<style>.controls {
display:flex;
flex-wrap:wrap;
gap:8px;
margin-bottom:12px;
} output {
display:block;
margin-block-start:12px;
overflow-wrap:anywhere;
}</style>
API
Treze temas Ant.Design 6.7.0 Combinado com público Svelte API. DirectoryTree, virtualização, scrollTo, createTree/getPath, arraste e solte e collapse motion Disponível.
| Tema | Exemplo ou restrição |
|---|---|
| Basic | checkable, disabled e teclas iniciais. |
| Controlled Tree | Divulgação e escolha múltipla. |
| draggable | Transferência de dados para onDrop, allowDrop, RTL e janela virtual. |
| load data asynchronously | Erro, repita, loadedKeys e limpeza. |
| Searchable | Luz de fundo e divulgação parental no modelo de exemplo. |
| Tree with line | showLine e showLeafIcon: boolean ou trecho. |
| Customize Icon | Snippet com TreeEventNode. |
| directory | DirectoryTree e seguindo expandAction. |
| Customize collapse/expand icon | switcherIcon e expandido de TreeEventNode. |
| Virtual scroll | Janela virtual, ambos os eixos e RTL; virtual=false Ative o modo nativo. |
| Scroll to nested node | TreeRef.scrollTo e ancestrais abrindo através de createTree/getPath. |
| Block Node | Largura total da string. |
| Custom semantic dom styling | Cinco slots semânticos, retornos de chamada e ConfigProvider.tree. |
Tree
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
draggable | boolean, predicado do nó original ou {nodeDraggable,icon}; icon=false Oculta a alça. | TreeDraggable<Data> | false |
allowDrop | Verifica o original dragNode/dropNode e posição relativa de -1/0/1, incluindo antes de drop. | TreeAllowDrop<Data> | — |
onDragStart | Inicie o HTML5 Drag com o evento nativo e o estado do nó. | (info: TreeDragInfo<Data>) => void | — |
onDragEnter | Orientação; expandedKeys Antes da abertura atrasada, as novas teclas chegam onExpand. | (info: TreeDragEnterInfo<Data>) => void | — |
onDragOver | Renovação da posição de transferência. | (info: TreeDragInfo<Data>) => void | — |
onDragLeave | Saindo do propósito de transferência. | (info: TreeDragInfo<Data>) => void | — |
onDragEnd | Conclusão do arrasto e liberação de recursos. | (info: TreeDragInfo<Data>) => void | — |
onDrop | Proprietário reorganiza treeData. dropPosition Contém o índice irmão mais -1/0/1; dropToGap Transferência diferencial. | (info: TreeDropInfo<Data>) => void | — |
motion | EIGEN CSS fase, preparo assíncrono e prazo; false Desativa a transição, null/undefined Ligue o padrão. | TreeMotionConfig | false | null | collapse |
prefixCls | Complete CSS prefixo do componente e suas partes. O suporte local não vazio é prioridade; String vazia e undefined Herdar ConfigProvider. O namespace do tópico é definido separadamente. | string | ConfigProvider.prefixCls + "-tree" |
treeData | Dados de origem tipados com chaves exclusivas estáveis. | readonly Data[] | [] |
fieldNames | Nomes dos campos de dados chave, cabeçalho e filho; Suportado por árvore e DirectoryTree. | TreeFieldNames | key/title/children |
classNames | Classes root/item/itemIcon/itemTitle/itemSwitcher: Registro ou retorno de chamada com propriedades. | TreeSemanticValue<TreeClassNames, Data> | — |
styles | CSS Strings de cinco slots semânticos: registro ou retorno de chamada com propriedades. | TreeSemanticValue<TreeStyles, Data> | — |
expandedKeys | divulgação controlada; Atualizado para onExpand. | readonly TreeKey[] | Status interno |
defaultExpandedKeys | Divulgação inicial. | readonly TreeKey[] | [] |
defaultExpandAll | Revelar a inicialização inicial dos dados. | boolean | false |
autoExpandParent | Divulgue as chaves controladas pelos pais. | boolean | false |
defaultExpandParent | Divulgue os pais ao inicializar. | boolean | true |
expandAction | Divulgação do cabeçalho; Modificado click Salva apenas a escolha. | false | "click" | "doubleClick" | false |
selectedKeys | Seleção de linha controlada. | readonly TreeKey[] | Status interno |
defaultSelectedKeys | Seleção inicial da linha. | readonly TreeKey[] | [] |
multiple | Árvore de múltipla escolha. | boolean | false |
selectable | Permitir seleção de linha. | boolean | true |
checkable | Mostrar caixa de seleção. | boolean | false |
checkStrictly | Marcas independentes de pais e filhos. | boolean | false |
checkedKeys | Marcas controladas; Em estrita mode objeto checked/halfChecked. | readonly TreeKey[] | TreeCheckedKeys | Status interno |
defaultCheckedKeys | Marcas de início. | readonly TreeKey[] | [] |
loadData | Carregando crianças. Atualizações do proprietário treeData. | (node: TreeEventNode) => PromiseLike<unknown> | — |
loadedKeys | Conjunto controlado de ramificações carregadas; Atualizado para onLoad. | readonly TreeKey[] | Status interno |
onExpand | Pedido de divulgação. | (keys, {expanded, node, nativeEvent}) => void | — |
onSelect | Seleção e selectedNodes. | (keys, info) => void | — |
onCheck | Marcas, halfCheckedKeys e checkedNodes. | (keys, TreeCheckInfo) => void | — |
onLoad | Download concluído com êxito. | (keys, {event, node}) => void | — |
filterTreeNode | Iluminação correspondente; Não exclui linhas. | (node: TreeEventNode) => boolean | — |
titleRender | O texto do seu nó. | Snippet<[Data]> | Campo de título de fieldNames |
showLine | Linhas de conexão. | boolean | {showLeafIcon: boolean | Snippet<[TreeEventNode]>} | false |
showIcon | Mostrar icon nó ou geral icon. | boolean | false |
icon | Ícone geral. | Snippet<[TreeEventNode]> | — |
switcherIcon | Ícone geral de divulgação; O download tem prioridade. | Snippet<[TreeEventNode]> | Padrão |
switcherLoadingIcon | Ícone de download. | Snippet<[TreeEventNode]> | loading |
blockNode | Largura da string por recipiente. | boolean | false |
height | Altura da viewport; undefined/0 Saída todas as linhas abertas sem limite de altura. | number | — |
virtual | Janela virtual em uma determinada altura; false Deixa todas as linhas do DOM. | boolean | ConfigProvider.virtual ?? true |
itemHeight | Estimativa de altura antes da medição; Zero desativa a janela virtual. | number | Tree tokens |
scrollWidth | Largura do conteúdo virtual para rolagem horizontal. | number | — |
itemScrollOffset | Rolagem automática do nó ativo. | number | 0 |
onScroll | Evento de rolagem do titular; Nativo onscroll também é compatível. | (event: UIEvent) => void | — |
tabIndex | Posição da árvore na ordem de foco por teclado. O atributo tabindex tem prioridade. | number | 0 |
onFocus | A árvore recebe o foco depois de determinar o nó ativo. | (event: FocusEvent) => void | — |
onBlur | A árvore perde o foco. | (event: FocusEvent) => void | — |
onKeyDown | Pressionamento de uma tecla depois de a árvore a processar. | (event: KeyboardEvent) => void | — |
onMouseDown | Pressionamento de um botão do rato antes de o foco mudar. | (event: MouseEvent) => void | — |
onContextMenu | Evento do menu de contexto da árvore depois de onRightClick do nó. | (event: MouseEvent) => void | — |
activeKey | Nodo de teclado ativo controlado. | TreeKey | null | Status interno |
onMouseEnter | Passando o mouse sobre o conteúdo da string, incluindo disabled nós. | ({event, node}) => void | — |
onMouseLeave | Deixe o conteúdo da string com o real TreeEventNode. | ({event, node}) => void | — |
onActiveChange | Alteração do nó ativo. | (key: TreeKey | null) => void | — |
TreeDataNode
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
key | ID estável exclusivo. | string | number | bigint | Obrigatório |
title | Nome do nó disponível. | TreeTitleContent<TreeDataNode> | --- |
children | Nós filhos. | readonly TreeDataNode[] | — |
isLeaf | Sinal de folha; false Permite que a ramificação seja carregada. | boolean | Por crianças/loadData |
disabled | desabilitando o nó e limitando as marcas. | boolean | false |
disableCheckbox | Desativar somente a caixa de seleção. | boolean | false |
checkable | Mostrar caixa de seleção deste nó. | boolean | General Checkable |
selectable | Permitir a seleção deste nó. | boolean | Selecionável geral |
switcherIcon | O ícone do nó tem prioridade sobre o renderizador geral e o download. | Snippet<[TreeEventNode]> | Total switcherIcon |
icon | Ícone do nó. | Snippet<[TreeEventNode]> | Ícone geral |
class | Classe de string de nós. | string | — |
style | CSS Strings de nós. | string | — |
TreeTitleContent Suporta strings, números, arrays aninhados e trechos com o nó de origem; boolean/null/undefined não são exibidos. Ícone e titleRender Salve o tipo de dados. bind:nativeElement Obtém a raiz externa, bind:this fornece TreeRef com focus/blur/scrollTo. height Especifica a viewport da janela virtual; virtual=false Deixa a rolagem normal.
DirectoryTree Herda TreeProps; Padrão expandAction="click", showIcon=true e blockNode=true. Múltipla escolha usa Ctrl/Meta e Shift.
createTree(dataOrGetter, config).getPath(key) Retorna TreeDataEntity[]: node, nós, key, pos, index, nível, pai e children. Um esquema fieldNames é suportado pelo modelo, árvore e DirectoryTree; A conversão de carga útil não é necessária.
Métodos TreeRef
TreeRef para árvore e DirectoryTree fornece focus(options?), blur() e scrollTo(config?). nativeElement Permanece um suporte ligável separado e limpo quando desmontado.
TreeScrollConfig Pega o número, {top,left}, key ou índice com align=top/bottom/auto e offset. offset — Número ou função pura TreeScrollOffset com getSize(startKey,endKey?). Desconhecido key não muda de posição; null/undefined Mostrar barra de rolagem.
left Define uma posição lógica não negativa em RTL. autoExpand A solicitação de chave apenas adiciona a chave de destino ao expandedKeys, sem ancestrais e onExpand. Após a desmontagem salva ref pára de executar ações com segurança.
Semantic DOM
Cinco slots semânticos estão disponíveis em classNames/styles e ConfigProvider.tree. Valores - registro ou retorno de chamada com propriedades; CSS Especificado por Strings. role=tree Usa aria-activedescendant, TreeItem informa o nível, seleção, marca e divulgação.
| Elemento | Atribuir |
|---|---|
root | raiz externa da árvore; Normal style Salva prioridade. |
item | String do nó; class/style Os dados são complementados com design semântico. |
itemIcon | Área do ícone do nó. |
itemTitle | Área de cabeçalho, incluindo trechos e conteúdo incorporado. |
itemSwitcher | Botão de abertura ou área de folha. |
| Elemento | Atribuir |
|---|---|
.ant-tree | Raiz externa, class/style e nativeElement. |
.ant-tree-list | Focalável role=tree com aria-activedescendant. |
.ant-tree-list-holder | Janela virtual de viewport ou rolagem nativa. |
.ant-tree-treenode | role=treeitem com status e nível. |
.ant-tree-switcher | Botão de divulgação excluído da ordem de tabulação. Botão |
.ant-tree-checkbox | Botão role=checkbox. |
.ant-tree-node-content-wrapper | Botão de seleção de strings. |
.ant-tree-iconEle | Área do ícone. |
.ant-tree-list-holder-inner | Strings montadas da janela virtual; A posição deve ser rolada. |
.ant-tree-list-scrollbar-vertical | Barra vertical da viewport vertical; Em RTL está localizado à esquerda. |
.ant-tree-list-scrollbar-horizontal | Tira horizontal em scrollWidth viewport mais ampla. |
.ant-tree-title | Título usado como um nome disponível. |
Tokens de design
Os tokens de árvore definem os tamanhos de linhas, switcher e aninhamento, bem como cores de estado. O exemplo muda o tema sem redefinir o nó selecionado e salva RTL. Os tokens de diretório definem as cores das linhas selecionadas DirectoryTree.
| Token | Atribuir |
|---|---|
titleHeight | Altura da string. |
switcherSize | Largura de abertura. |
indentSize | Etapa de nidificação horizontal. |
nodeHoverBg | Passe o plano de fundo. |
nodeHoverColor | Hover-text. |
nodeSelectedBg | Plano de fundo do nó selecionado. |
nodeSelectedColor | Texto do nó selecionado. |
directoryNodeSelectedBg | Selecionado fundo de string DirectoryTree. |
directoryNodeSelectedColor | Selecionado Texto de string DirectoryTree. |
| Token | Valor |
|---|---|
colorBgContainer | #ffffff |
colorText | rgba(0,0,0,0.88) |
colorTextDisabled | rgba(0,0,0,0.25) |
colorPrimary | #2f54eb |
controlInteractiveSize | 16 |
fontSize | 14 |
paddingXS | 8 |
FAQ
Selecionando uma string e uma marca - um estado?
selectedKeys Controla a escolha, checkedKeys — Marcas, expandedKeys — Divulgação. Leve-os através de onSelect, onCheck e onExpand separadamente.
Como checkStrictly funciona?
em false Pais e filhos estão ligados e podem receber notas parciais. Em true as marcas são independentes e onCheck retorna checked/halfChecked.
Por que defaultExpandAll não revelou os nós carregados?
Os propriedades iniciais já foram lidos. Para obter dados posteriores, atualize expandedKeys ou crie uma árvore após o carregamento.
filterTreeNode esconde strings que não combinam?
Não, ele destaca os nós. A divulgação de pais, filtragem de dados separadas e iluminação de texto é organizada pelo aplicativo.
Existe virtualização e scrollTo?
Sim. Positivo height e habilitado virtual Defina a janela virtual. TreeRef.scrollTo Funciona com coordenadas, chave ou índice; A divulgação dos ancestrais é organizada pelo proprietário.
Como ativar a animação de arrastar e soltar?
draggable Permite a transferência, mas treeData atualiza o proprietário para onDrop. A animação padrão já está ativada; motion=false Desative-o. Os exemplos acima mostram os dois modos.
Como controlar a partir do teclado?
Use setas, Home/Fim, Entrar e Espaço. O foco permanece na árvore; activeKey Comunica o nó ativo separadamente da seleção e das marcas.