Pular para o conteúdo

Tree

Estrutura de árvore hierárquica para exibir dados aninhados.

import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'

Árvore Básica

Árvore simples com nós expansíveis.

Parent Node
Child Node 1
Leaf Node 1
Leaf Node 2
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'

function App() {
  const basicTreeData: TreeDataNode[] = [
    {
      key: '0',
      title: 'Parent Node',
      children: [
        {
          key: '0-0',
          title: 'Child Node 1',
          children: [
            { key: '0-0-0', title: 'Leaf Node 1' },
            { key: '0-0-1', title: 'Leaf Node 2' },
          ],
        },
        {
          key: '0-1',
          title: 'Child Node 2',
          children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
        },
      ],
    },
  ]
  
  return (
      <Tree treeData={basicTreeData} defaultExpandedKeys={['0', '0-0']} />
    )
}

export default App

Com Checkbox

Árvore com seleção por checkbox.

Parent Node
Child Node 1
Leaf Node 1
Leaf Node 2
Child Node 2
Leaf Node 3

Checked: None

import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { useState } from 'react'

function App() {
  const basicTreeData: TreeDataNode[] = [
    {
      key: '0',
      title: 'Parent Node',
      children: [
        {
          key: '0-0',
          title: 'Child Node 1',
          children: [
            { key: '0-0-0', title: 'Leaf Node 1' },
            { key: '0-0-1', title: 'Leaf Node 2' },
          ],
        },
        {
          key: '0-1',
          title: 'Child Node 2',
          children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
        },
      ],
    },
  ]
  
  const [checkedKeys, setCheckedKeys] = useState<string[]>([])
  
  return (
      <Tree
        treeData={basicTreeData}
        checkable
        checkedKeys={checkedKeys}
        onCheck={setCheckedKeys}
        defaultExpandedKeys={['0', '0-0', '0-1']}
      />
      <p className="mt-4 text-sm">Checked: {checkedKeys.join(', ') || 'None'}</p>
    )
}

export default App

Selecionável

Árvore com seleção de nós.

Parent Node
Child Node 1
Leaf Node 1
Leaf Node 2
Child Node 2
Leaf Node 3

Selected: None

import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { useState } from 'react'

function App() {
  const basicTreeData: TreeDataNode[] = [
    {
      key: '0',
      title: 'Parent Node',
      children: [
        {
          key: '0-0',
          title: 'Child Node 1',
          children: [
            { key: '0-0-0', title: 'Leaf Node 1' },
            { key: '0-0-1', title: 'Leaf Node 2' },
          ],
        },
        {
          key: '0-1',
          title: 'Child Node 2',
          children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
        },
      ],
    },
  ]
  
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])
  
  return (
      <Tree
        treeData={basicTreeData}
        selectable
        selectedKeys={selectedKeys}
        onSelect={setSelectedKeys}
        defaultExpandedKeys={['0', '0-0', '0-1']}
      />
      <p className="mt-4 text-sm">Selected: {selectedKeys.join(', ') || 'None'}</p>
    )
}

export default App

Seleção Múltipla

Permite selecionar múltiplos nós.

Parent Node
Child Node 1
Leaf Node 1
Leaf Node 2
Child Node 2
Leaf Node 3
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { useState } from 'react'

function App() {
  const basicTreeData: TreeDataNode[] = [
    {
      key: '0',
      title: 'Parent Node',
      children: [
        {
          key: '0-0',
          title: 'Child Node 1',
          children: [
            { key: '0-0-0', title: 'Leaf Node 1' },
            { key: '0-0-1', title: 'Leaf Node 2' },
          ],
        },
        {
          key: '0-1',
          title: 'Child Node 2',
          children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
        },
      ],
    },
  ]
  
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])
  
  return (
      <Tree
        treeData={basicTreeData}
        selectable
        multiple
        selectedKeys={selectedKeys}
        onSelect={setSelectedKeys}
        defaultExpandedKeys={['0', '0-0', '0-1']}
      />
    )
}

export default App

Mostrar Linhas

Exibe linhas conectando os nós.

src
components
Button.tsx
Input.tsx
App.tsx
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'

function App() {
  const fileTreeData: TreeDataNode[] = [
    {
      key: 'src',
      title: 'src',
      children: [
        {
          key: 'components',
          title: 'components',
          children: [
            { key: 'Button.tsx', title: 'Button.tsx' },
            { key: 'Input.tsx', title: 'Input.tsx' },
          ],
        },
        { key: 'App.tsx', title: 'App.tsx' },
      ],
    },
  ]
  
  return (
      <Tree
        treeData={fileTreeData}
        showLine
        defaultExpandedKeys={['src', 'components']}
      />
    )
}

export default App

Mostrar Ícone

Exibe ícones personalizados para nós.

src
App.tsx
index.tsx
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { FolderIcon, DocumentIcon } from '@aster-ui/icons/solid'

function App() {
  const treeDataWithIcons: TreeDataNode[] = [
    {
      key: 'src',
      title: 'src',
      icon: <FolderIcon size="sm" />,
      children: [
        { key: 'App.tsx', title: 'App.tsx', icon: <DocumentIcon size="sm" /> },
        { key: 'index.tsx', title: 'index.tsx', icon: <DocumentIcon size="sm" /> },
      ],
    },
  ]
  
  return (
      <Tree treeData={treeDataWithIcons} showIcon defaultExpandedKeys={['src']} />
    )
}

export default App

Padrão Composto

Use Tree.Node para estrutura de árvore declarativa.

Parent Node
Child Node 2
import { Tree } from 'asterui'

function App() {
  return (
      <Tree defaultExpandedKeys={['parent']}>
        <Tree.Node key="parent" title="Parent Node">
          <Tree.Node key="child-1" title="Child Node 1">
            <Tree.Node key="leaf-1" title="Leaf Node 1" />
            <Tree.Node key="leaf-2" title="Leaf Node 2" />
          </Tree.Node>
          <Tree.Node key="child-2" title="Child Node 2" />
        </Tree.Node>
      </Tree>
    )
}

export default App

Cores de Checkbox

Personalize a aparência do checkbox com cores DaisyUI.

Parent Node
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'

function App() {
  const basicTreeData: TreeDataNode[] = [
    {
      key: '0',
      title: 'Parent Node',
      children: [
        {
          key: '0-0',
          title: 'Child Node 1',
          children: [
            { key: '0-0-0', title: 'Leaf Node 1' },
            { key: '0-0-1', title: 'Leaf Node 2' },
          ],
        },
        {
          key: '0-1',
          title: 'Child Node 2',
          children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
        },
      ],
    },
  ]
  
  return (
      <Tree
        treeData={basicTreeData}
        checkable
        checkboxColor="success"
        checkboxSize="md"
        defaultExpandedKeys={['0']}
      />
    )
}

export default App

Seleção Estrita

Desacopla a relação pai-filho do checkbox.

Parent Node
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { useState } from 'react'

function App() {
  const basicTreeData: TreeDataNode[] = [
    {
      key: '0',
      title: 'Parent Node',
      children: [
        {
          key: '0-0',
          title: 'Child Node 1',
          children: [
            { key: '0-0-0', title: 'Leaf Node 1' },
            { key: '0-0-1', title: 'Leaf Node 2' },
          ],
        },
        {
          key: '0-1',
          title: 'Child Node 2',
          children: [{ key: '0-1-0', title: 'Leaf Node 3' }],
        },
      ],
    },
  ]
  
  const [checkedKeys, setCheckedKeys] = useState<string[]>([])
  
  return (
      <Tree
        treeData={basicTreeData}
        checkable
        checkStrictly
        checkedKeys={checkedKeys}
        onCheck={setCheckedKeys}
        defaultExpandedKeys={['0']}
      />
    )
}

export default App

Carregamento Assíncrono

Carrega nós filhos assincronamente ao expandir.

Expand to load
Expand to load
import { Tree } from 'asterui'
import type { TreeDataNode } from 'asterui'
import { useState } from 'react'

function App() {
  const [treeData, setTreeData] = useState<TreeDataNode[]>([
    { key: '0', title: 'Expand to load' },
    { key: '1', title: 'Expand to load' },
  ])
  
  const loadData = async (node: TreeDataNode) => {
    await new Promise(resolve => setTimeout(resolve, 1000))
    setTreeData(prev => {
      const update = (nodes: TreeDataNode[]): TreeDataNode[] =>
        nodes.map(n => n.key === node.key
          ? { ...n, children: [
              { key: `${n.key}-0`, title: 'Child 1', isLeaf: true },
              { key: `${n.key}-1`, title: 'Child 2', isLeaf: true },
            ]}
          : { ...n, children: n.children ? update(n.children) : undefined }
        )
      return update(prev)
    })
  }
  
  return (
      <Tree treeData={treeData} loadData={loadData} />
    )
}

export default App
PropriedadeDescriçãoTipoPadrão
treeDataEstrutura de dados da árvore (alternativa ao padrão composto)TreeDataNode[][]
childrenFilhos Tree.Node para padrão compostoReact.ReactNode-
checkableMostrar checkbox para cada nóbooleanfalse
checkboxColorCor do checkbox (DaisyUI)'primary' | 'secondary' | 'accent' | 'neutral' | 'info' | 'success' | 'warning' | 'error''primary'
checkboxSizeTamanho do checkbox (DaisyUI)'xs' | 'sm' | 'md' | 'lg' | 'xl''sm'
checkedKeysChaves marcadas controladasstring[]-
defaultCheckedKeysChaves marcadas padrãostring[][]
checkStrictlyDesacoplar relação pai-filho do checkboxbooleanfalse
onCheckCallback quando nó é marcado(keys: string[], info: { node, checked }) => void-
selectableHabilitar seleção de nósbooleantrue
selectedKeysChaves selecionadas controladasstring[]-
defaultSelectedKeysChaves selecionadas padrãostring[][]
onSelectCallback quando nó é selecionado(keys: string[], info: { node, selected }) => void-
multiplePermitir seleção múltiplabooleanfalse
expandedKeysChaves expandidas controladasstring[]-
defaultExpandedKeysChaves expandidas padrãostring[][]
defaultExpandAllExpandir todos os nós por padrãobooleanfalse
autoExpandParentAuto expandir nós paibooleantrue
onExpandCallback quando nó é expandido(keys: string[], info: { node, expanded }) => void-
showLineMostrar linhas conectandobooleanfalse
showIconMostrar ícones dos nósbooleanfalse
blockNodeFazer nós ocuparem espaço horizontalbooleanfalse
loadDataFunção de carregamento de dados assíncrono(node: TreeDataNode) => Promise<void>-
classNameClasses CSS adicionaisstring-

O componente Tree implementa o padrão completo de árvore WAI-ARIA:

  • role="tree" no container e role="treeitem" nos nós
  • aria-expanded indica estado de expansão do nó
  • aria-selected indica estado de seleção
  • aria-checked indica estado do checkbox (com "mixed" para indeterminado)
  • aria-disabled indica estado desabilitado
  • aria-level indica profundidade de aninhamento
TeclaAção
Move foco para próximo nó visível
Move foco para nó visível anterior
Expande nó recolhido, ou move para primeiro filho
Recolhe nó expandido
Enter / SpaceAlterna checkbox, seleciona nó, ou expande/recolhe
HomeMove foco para primeiro nó
EndMove foco para último nó visível