Table
Tabelas: colunas, filtros, classificação, seleção, paginação, divulgação, rolagem e dados do servidor.
Quando usar
A tabela mostra registros com o mesmo conjunto de campos: participantes, pedidos ou tarefas. As colunas ajudam a comparar valores, classificar e filtrar dados, selecionar linhas para ação geral. As entradas aninhadas podem ser abertas dentro da tabela. Para navegar pela hierarquia de seções, Tree é adequado.
Passe as entradas via dataSource. As colunas podem ser definidas com array columns ou declaradas dentro da tabela via Table.Column e Table.ColumnGroup. Exemplo de grupo Mostra colunas aninhadas.
Registros e colunas
Cada entrada precisa de uma chave estável exclusiva: record.key ou rowKey. Ele vincula DOM, seleção e divulgação. Use uma string ou um número finito salvando a chave ao classificar, editar e recuperar uma nova página.
| Tarefa | Configuração | Exemplo |
|---|---|---|
| Mostrar entradas tipadas | dataSource, columns, rowKey |
Mesa regular |
| Classifique e filtre localmente | sorter, onFilter na coluna |
Filtros e classificação |
| Selecionar linhas para ação | rowSelection, selectedRowKeys |
escolha e ação |
| Mostrar uma hierarquia de registros | children |
Linhas de árvores |
| Carregue páginas com o aplicativo | mode="server", onChange |
Modo de servidor |
| Abra os detalhes da entrada | expandable |
Linhas desabilitadas |
em dataIndex String Define a chave de registro e a matriz define o caminho para o valor aninhado. Snippet render Obtém uma entrada, um índice entre vizinhos e valor original.
A chave da coluna pode ser definida explicitamente por uma string ou número. Sem key a tabela leva dataIndex, e para uma coluna sem um campo — sua posição. Para colunas que mudam de lugar, defina uma chave estável. Na filtragem e classificação de eventos, a chave é sempre string.
Propriedade column Especifica as configurações gerais do coluna. No modo tableLayout="auto", a largura mínima minWidth é válida. Use ellipsis para texto longo e { showTitle: false } se o texto completo mostrar sua própria dica de ferramenta. Exemplo com pedidos.
em shouldCellUpdate Compare a nova e última entrada recebida se o conteúdo da célula depender de vários campos específicos. Substitua a entrada alterada por um novo objeto. Exemplo com tarefas de edição.
O aplicativo pode alterar a composição dos colunas por meio de hidden. Os filtros de colunas de classificação e ocultação continuam funcionando. Exemplo com interruptor de coluna.
em children Insira as colunas que precisam de um cabeçalho comum. Configuração responsive A coluna ou grupo de nível superior define as larguras da janela. Exemplo de carga de trabalho.
Defina colSpan ou rowSpan para mesclar células. No cabeçalho, as dimensões são definidas na coluna ou por meio de onHeaderCell e nas linhas de dados - até onCell. O tamanho zero permite que você pule uma célula cujo lugar já esteja ocupado pelo sindicato. Release Check Exemplo.
Em onRow e onHeaderRow Você pode retornar os atributos e manipuladores Svelte para strings e cabeçalhos. O índice da linha se refere a toda a página aberta. O índice da string da tampa corresponde ao seu nível, começando do zero.
Classificação, filtros e páginas
no modo cliente sorter organiza os registros e onFilter verifica-os de acordo com as condições aplicadas. No modo de servidor, o aplicativo recebe uma solicitação via onChange e passa na página finalizada.
Especifique multiple para colunas classificáveis para aplicar vários critérios. A prioridade mais alta é comparada primeiro. O aplicativo pega a lista sorters do evento e define a direção para sortOrder de cada coluna. showSorterTooltip Mostra a seguinte ação. Exemplo de classificação por comando e número de tarefas.
As opções de filtro aninhadas são definidas em children. Se filterMode: 'tree' eles podem ser abertos e filterSearch ajuda a encontrar o item desejado. Snippet title Obtém os filtros aplicados e as direções de classificação. Exemplo de pesquisa de comandos.
Para definir a condição inicial, use defaultFilteredValue. Para controlar a partir do aplicativo, passe filteredValue e atualize-o por evento onChange. Em seu painel filterDropdown, você pode alterar o rascunho por meio de setSelectedKeys e aplicá-lo por meio de confirm(). getPopupContainer Especifica o contêiner do painel. Exemplo numérico.
filterIcon e filterDropdown também aceitam conteúdos estáticos. Se o painel do usuário aplicar a condição sem onFilter, ele será passado para onChange e as linhas permanecerão visíveis. Outros filtros ativos continuam a selecionar registros. A assinatura da opção filters[].text pode conter um número ou um trecho. Para pesquisar a assinatura composta, defina a função filterSearch.
Estado disponível bind:sorter, bind:filters, bind:current e bind:pageSize. Os propriedades default correspondentes definem apenas o estado local inicial. Reinicializar o filtro ou a classificação é feita atribuindo o estado atual. Filtros gerenciados Mostre esse reset separadamente.
Após a filtragem, a tabela retorna à primeira página. Os parâmetros pagination.placement permitem que você mostre a navegação acima da mesa, sob ela ou em ambos os lados. Ambos os painéis usam uma página atual e um tamanho. Exemplo de paginação.
no servidor mode Passe a página atual dataSource, total total e loading. A tabela não executa a solicitação em si. Exemplo de servidor Usa um simulador local e um modelo que descarta resultados obsoletos, repete a última solicitação e é liberado na desmontagem.
Em loading Você pode passar as configurações Spin com atraso e assinatura. Embora o resultado seja desconhecido, passe undefined ou null para dataSource. Um array vazio denota o resultado sem registros. Por meio de locale, as assinaturas e o estado vazio da tabela específica são definidos. Carregando e vazio Exemplo de status.
Seleção, divulgação e rolagem
em rowSelection.type selecione checkbox para várias linhas ou radio para uma. No modo de caixa de seleção, Shift permite selecionar um intervalo e selections adiciona um menu para comandos de massa. Exemplo de modos de seleção.
As chaves gerenciadas são definidas como rowSelection.selectedRowKeys e atualizadas em rowSelection.onChange. Para as páginas do servidor preserveSelectedRowKeys Salva as entradas já selecionadas ao alterar dataSource. Suportado também bind:selectedRowKeys na mesa.
Propriedade expandedRowRender Adiciona uma string de detalhes. A propriedade rowExpandable determina para quais registros está disponível. No exemplo “Tabela necessária” em detalhes, uma tabela com as tarefas do participante é aberta.
notas na matriz de colunas Table.EXPAND_COLUMN e Table.SELECTION_COLUMN defina as localizações dos elementos de serviço. Para o seu botão, passe expandIcon nas configurações de abertura ou em ConfigProvider.table. Em renderCell você pode encerrar o controle de seleção regular, por exemplo, em uma dica. forceRender O modo salva o rascunho quando os detalhes são minimizados enquanto a linha está no DOM. Exemplo com.
scroll.x Define a largura mínima da tabela, scroll.y Limita a área de rolagem vertical. fixed=true/start/end Corrige as colunas nas arestas lógicas, levando em consideração RTL; Se houver falta de espaço, a fixação será desligada. Exemplo de rolagem Mostra o cabeçalho e as colunas dentro de sua região scroll.
caption e aria-label Forneça o nome da tabela disponível, showHeader Controla os cabeçalhos das colunas, rowHoverable — linhas retroiluminadas. O design pode ser definido via class/style, column.className, rowClassName e componente Tokens de design (design tokens).
Use classNames e styles para projetar elementos específicos, como cabeçalho ou célula do corpo. Ambas as propriedades recebem um objeto ou função das propriedades da tabela. Component Snippet components.body.row Permite adicionar marcações de linha. Passe os atributos recebidos, o trecho filho e ref ao seu elemento nativo para salvar eventos e medidas. Exemplo de design de strings.
A tabela herda ConfigProvider.prefixCls com sufixo -table. Local não vazio prefixCls Especifica o nome completo wrapper, linhas, células, classificação e elementos de filtro; Empty String/undefined Retorna o prefixo geral. Checkbox, Pagination e Button permitir seu prefixo comum independentemente da tabela. CSS Prefixos da tabela também mostra o editor de strings aberto, RTL e um namespace separado CSS variáveis.
dropdownPrefixCls Especifica o nome da lista de filtros com sufixo -menu. Shell de painel, caixa de seleção e botão herdam um prefixo comum.
em Assinatura da amostra Snippet caption Especifica o nome da tabela disponível e a área de rolagem. role e aria-* Consulte o elemento da tabela e id e data-* ao seu recipiente interno.
Mudança de nome Salva o DOM do editor, seu texto, foco, seleção e FormData, bem como seleção, abertura, página, classificação, rascunho de filtro aberto e rolagem. Tokens theme.components.Table e marcador ant-table-css-var não são renomeados junto com as classes. Namespace theme.cssVar.prefix é definido separadamente; A variável de serviço nested-border-top usa o prefixo geral do provedor sem pontos. Temas claros, escuros e compactos funcionam sem variáveis CSS. Ao alterar o prefixo, a altura da tabela junto com a paginação é preservada.
Rolagem e totais virtuais
Para desenhar apenas a janela Linhas Visíveis, ative virtual e defina o numérico scroll.x e scroll.y em pixels. Após a hidratação, a tabela especifica a altura das linhas. A seleção de linhas funciona em toda a página atual, incluindo entradas fora da janela. Exemplo com log de verificação.
Obtenha TableRef via bind:this e ligue para scrollTo com uma posição vertical, chave ou índice de linha na página atual. Através de onScroll você pode rastrear a posição vertical da janela. A configuração scrollToFirstRowOnChange determina se deve rolar a tabela para o início após classificar, filtrar e alterar a página.
Snippet components.body Pode exibir linhas em sua área de rolagem. Passe o contêiner info.ref e info.onScroll para sincronizar a posição horizontal da tampa e salve a transição da chave. Em ConfigProvider.table você pode definir o rowKey geral e scroll geral. Local scroll Substitui toda a configuração. Exemplo com lista de verificação própria.
Snippets title, footer e summary Receba as entradas da página atual. Table.Summary Exibe as linhas finais dentro de tfoot. Table.Summary.Cell Os índices levam em consideração as colunas de seleção e divulgação visíveis. Nas configurações summary defina fixed: 'bottom' ou fixed: 'top' para consolidar o resultado em uma tabela com altura ou co sticky limitada.
sticky Proteja o cabeçalho e a barra horizontal adicional ao rolar a página. A propriedade getContainer permite que você ligue a âncora a outra área de rolagem. Em Exemplo com resultados o relatório é rolado para dentro do cartão e o resultado é recalculado ao alterar a página.
Linhas de árvores
Passe as entradas filho na matriz children. Se o campo for nomeado de forma diferente, especifique expandable.childrenColumnName. A chave deve ser única em toda a mesa, incluindo galhos dobrados. Exemplo de tarefas de lançamento Mostra três níveis de nidificação.
Defina a abertura inicial via defaultExpandedRowKeys ou abra toda a página inicial via defaultExpandAllRows. Se o aplicativo for controlado pelo aplicativo, atualize expandedRowKeys dentro expandable para o evento onExpandedRowsChange. A indentação de um nível define indentSize.
Por padrão, as strings são independentes. Se rowSelection indicar checkStrictly: false, a marca pai se estende até a prole disponível. Se apenas parte da ramificação for selecionada, o pai exibe uma marca parcial. A caixa de cabeçalho seleciona as linhas disponíveis da página atual, incluindo os descendentes nas ramificações recolhidas.
Ordens de classificação locais Linhas vizinhas em cada nível. O filtro verifica os registros em todos os níveis. Se o pai não passar o filtro, sua ramificação ficará oculta. Quando paginados, as strings de nível superior são levadas em consideração e os descendentes permanecem na página principal.
Exemplos
Nome | Comando | Tarefas |
|---|---|---|
| Анна | Разработка | 18 |
| Борис | Дизайн | 9 |
| Вера | Поддержка | 0 |
| Глеб | Разработка | 24 |
| Дарья | Дизайн | 12 |
| Егор | Поддержка | 15 |
Mesa regular
columns, dataSource e esta assinatura caption.
Basic.svelte<script lang="ts"> import { Table } from '@woodger/antd'; import { columns, members } from './data'; </script> <Table dataSource={(members)} columns={(columns)} caption={("Documentos participantes")} pagination={(false)} />data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Nome | Comando | Tarefas | |
|---|---|---|---|
| Анна | Разработка | 18 | |
| Борис | Дизайн | 9 | |
| Вера | Поддержка | 0 |
escolha e ação
Checkbox Desabilitado Gravação e salvamento de teclas entre as páginas.
Selection.svelte<script lang="ts"> import { Button, Table, type TableKey } from '@woodger/antd'; import { columns, members } from './data'; let selected = $state<TableKey[]>([]); let result = $state(''); </script> <style> .actions { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; } output { display: block; margin-top: 16px; } </style> <div class="actions"><Button disabled={!selected.length} onclick={() => { result = ("Processado: " + String((selected.length)) + ""); }}>{("Lidar com linhas selecionadas")}</Button> <Button onclick={() => { selected = []; result = ''; }} >{("Seleção de linha clara")}</Button></div> <Table dataSource={(members)} columns={(columns)} caption={("Seleção de participantes")} defaultPageSize={3} rowSelection={{ getCheckboxProps: row => ({ disabled: !row.active, 'aria-label': `Selecione o membro ${row.name}` }) }} bind:selectedRowKeys={selected} pagination={({ 'aria-label': "Participante Selecione as páginas" })} /> <output aria-label={("Selecionando linhas")}>{(selected.join(', ') || '—')}{(result ? `; ${result}` : '')}</output>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Participante | Tarefas | |
|---|---|---|
| Anna | 18 | |
| Boris | 9 | |
| fé | 0 | |
| GLEB | 24 | |
| Daria | 12 | |
| egor | 15 |
Modos e comandos de seleção
Alterne uma seleção de participante ou use o menu Ações em massa.
SelectionModes.svelte<script lang="ts"> import { Flex, Switch, Table, type TableKey, type TableRowSelection } from '@woodger/antd'; import { members, type Member } from './data'; const switchId = $props.id(); let single = $state(false); let selectedRowKeys = $state<TableKey[]>([]); const rowSelection = $derived<TableRowSelection<Member>>({ type: single ? 'radio' : 'checkbox', selectedRowKeys, onChange: keys => { selectedRowKeys = keys; }, getCheckboxProps: member => ({ 'aria-label': (member.name), disabled: !member.active }), selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE] }); function changeMode(next: boolean) { single = next; if (single) { selectedRowKeys = selectedRowKeys.slice(0, 1); } } </script> <Flex vertical gap="medium"> <Flex align="center" gap="small"> <Switch id={switchId} checked={single} onCheckedChange={changeMode} /> <label for={switchId}>{("Selecione um participante")}</label> </Flex> <Table aria-label={("Modos de Seleção de Participantes")} dataSource={members} columns={[ { key: 'name', title: ("Participante"), rowScope: 'row', render: name }, { key: 'tasks', title: ("Tarefas"), dataIndex: 'tasks', align: 'right' } ]} {rowSelection} size="small" pagination={false} /> </Flex> {#snippet name(member: Member)} {(member.name)} {/snippet}data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Tarefa de lançamento | Artista | |
|---|---|---|
| Preparação para lançamentos | Anna | |
| Manual de atualização | Anna | |
| Colete o pacote | Boris | |
| Lançamento do relatório | Boris |
Linhas de árvores
Expanda o problema e tente selecionar toda a ramificação ou linhas individuais.
<script lang="ts">
import { Flex, Switch, Table, type TableColumn } from '@woodger/antd';
interface Task {
key: string;
title: string;
owner: string;
children?: readonly Task[];
}
const switchId = $props.id();
const tasks: readonly Task[] = [
{
key: 'prepare',
title: "Preparação para lançamentos",
owner: 'Anna',
children: [
{
key: 'guide',
title: "Manual de atualização",
owner: 'Anna',
children: [
{ key: 'review', title: "Verifique os exemplos", owner: 'Vera' }
]
},
{ key: 'build', title: "Colete o pacote", owner: 'Boris' }
]
},
{ key: 'announce', title: "Lançamento do relatório", owner: 'Boris' }
];
const columns: TableColumn<Task>[] = [
{ key: 'task', title: "Tarefa de lançamento", dataIndex: 'title', rowScope: 'row' },
{ key: 'owner', title: "Artista", dataIndex: 'owner' }
];
let linkedSelection = $state(true);
</script>
<Flex vertical gap="medium">
<Flex align="center" gap="small">
<Switch id={switchId} bind:checked={linkedSelection} />
<label for={switchId}>{("Seleção de linha relacionada")}</label>
</Flex>
<Table
aria-label={("Tarefas de lançamento")}
dataSource={(tasks)}
columns={(columns)}
expandable={{ defaultExpandedRowKeys: ['prepare'], expandRowByClick: true }}
rowSelection={{
checkStrictly: !linkedSelection,
getCheckboxProps: task => ({ 'aria-label': task.title })
}}
pagination={false}
/>
</Flex>
Comando | ||
|---|---|---|
| Анна | Разработка | 18 |
| Борис | Дизайн | 9 |
| Вера | Поддержка | 0 |
| Глеб | Разработка | 24 |
| Дарья | Дизайн | 12 |
| Егор | Поддержка | 15 |
Filtros e classificação
Comparador, onFilter e um objeto TableChange.
FilterSort.svelte<script lang="ts"> import { Table, type TableChange } from '@woodger/antd'; import { filterColumns, members, type Member } from './data'; let result = $state('—'); function changed(change: TableChange<Member>) { result = ("" + String((change.action)) + ": " + String((change.currentDataSource.map( row => row.name ).join(', '))) + ""); } </script> <style> output { display: block; margin-top: 16px; overflow-wrap: anywhere; } </style> <Table dataSource={(members)} columns={(filterColumns)} caption={("Filtros e Participantes Classificando")} pagination={(false)} onChange={changed} /> <output aria-label={("Alterar Tabela")}>{result}</output>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Participante | ||
|---|---|---|
| Anna | Desenvolvimento | 18 |
| Boris | Design | 9 |
| fé | Suporte | 0 |
| GLEB | Desenvolvimento | 24 |
| Daria | Design | 12 |
| egor | Suporte | 15 |
Classificação em várias colunas
Classifique os participantes dentro das equipes. A equipe tem a primeira prioridade.
MultiSort.svelte<script lang="ts"> import { Button, Flex, Table, type TableChange, type TableColumn, type TableSorter } from '@woodger/antd'; import { members, type Member } from './data'; let sorters = $state<TableSorter[]>([]); const columns = $derived<TableColumn<Member>[]>([ { key: 'name', title: ("Participante"), rowScope: 'row', render: name }, { key: 'team', title: ("Comando"), render: team, sortOrder: columnOrder('team'), sorter: { compare: compareTeams, multiple: 2 } }, { key: 'tasks', title: ("Tarefas"), dataIndex: 'tasks', align: 'end', sortOrder: columnOrder('tasks'), sorter: { compare: (a, b) => a.tasks - b.tasks, multiple: 1 } } ]); function columnOrder(key: string) { const criterion = sorters.find(sorter => sorter.columnKey === key); return criterion?.order ?? null; } function compareTeams(left: Member, right: Member) { const leftName = (left.team); const rightName = (right.team); return leftName.localeCompare(rightName, "pt"); } function acceptSort(change: TableChange<Member>) { if (change.action === 'sort') { sorters = change.sorters ?? []; } } </script> {#snippet name(member: Member)}{(member.name)}{/snippet} {#snippet team(member: Member)}{(member.team)}{/snippet} <Flex vertical gap="medium"> <div> <Button disabled={!sorters.length} onclick={() => { sorters = []; }}> {("Redefinir a classificação")} </Button> </div> <Table aria-label={("Tarefas de Comando")} dataSource={members} {columns} showSorterTooltip={{ target: 'sorter-icon' }} onChange={acceptSort} size="small" pagination={false} /> </Flex>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Participante | Comando(1) Filtro: |
|---|---|
| Boris | Design |
| Daria | Design |
Pesquisa na árvore de filtros
Encontre o comando no filtro. Reset Retorna a seleção original de "design".
TreeFilters.svelte<script lang="ts"> import { Table, type TableColumn, type TableColumnTitleProps, type TableFilterOption } from '@woodger/antd'; import { members, type Member } from './data'; const wholeProduct = 'product'; const teamOptions: TableFilterOption[] = [ { text: productLabel, value: wholeProduct, children: [ { text: "Desenvolvimento", value: "Desenvolvimento" }, { text: "Design", value: "Design" } ] }, { text: "Suporte", value: "Suporte" } ]; function matchesTeam(input: string, option: TableFilterOption) { const label = option.value === wholeProduct ? "Comando do Produto" : String(option.value); return (label).toLocaleLowerCase().includes(input.trim().toLocaleLowerCase()); } const columns: TableColumn<Member>[] = [ { key: 'name', title: "Participante", rowScope: 'row', render: name }, { key: 'team', title: teamHeading, render: team, filters: teamOptions, filterMode: 'tree', filterSearch: matchesTeam, defaultFilteredValue: ["Design"], filterResetToDefaultFilteredValue: true, onFilter: (value, member) => value === wholeProduct ? member.team !== "Suporte" : value === member.team } ]; </script> {#snippet productLabel()}<strong>{("Comando do Produto")}</strong>{/snippet} {#snippet name(member: Member)}{(member.name)}{/snippet} {#snippet team(member: Member)}{(member.team)}{/snippet} {#snippet teamHeading({ filters }: TableColumnTitleProps<Member>)} {@const count = filters.team?.length ?? 0} {("Comando")}{#if count} ({count}){/if} {/snippet} <Table aria-label={("Membros da equipe")} dataSource={members} columns={(columns)} size="small" pagination={false} />data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Participante | Tarefas |
|---|---|
| Anna | 18 |
| Boris | 9 |
| fé | 0 |
| GLEB | 24 |
| Daria | 12 |
| egor | 15 |
Painel de filtro próprio
Defina o número mínimo de tarefas e aplique a condição.
CustomFilter.svelte<script lang="ts"> import { Button, Checkbox, Flex, InputNumber, Table, type TableChange, type TableColumn, type TableFilterDropdownProps, type TableFilterValue } from '@woodger/antd'; import { members, type Member } from './data'; let popupHost = $state<HTMLDivElement>(); let minimum = $state<TableFilterValue[]>([]); let highlightOnly = $state(false); function meetsMinimum(value: TableFilterValue | undefined, member: Member) { return typeof value === 'number' && member.tasks >= value; } const columns = $derived<TableColumn<Member>[]>([ { key: 'name', title: ("Participante"), rowScope: 'row', render: name }, { key: 'tasks', title: ("Tarefas"), dataIndex: 'tasks', align: 'end', filteredValue: minimum, filterDropdown: thresholdPanel, filterIcon: '≥', render: tasks, filterDropdownProps: { placement: 'bottomRight' }, onFilter: highlightOnly ? undefined : meetsMinimum } ]); function acceptFilter(change: TableChange<Member>) { if (change.action === 'filter') { minimum = change.filters?.tasks ?? []; } } </script> <style> .filter-popup-host { display: grid; grid-template-columns: minmax(0, 1fr); gap: 16px; } </style> {#snippet name(member: Member)}{(member.name)}{/snippet} {#snippet tasks(member: Member)} {#if highlightOnly && meetsMinimum(minimum[0], member)} <strong>{member.tasks}</strong> {:else} {member.tasks} {/if} {/snippet} {#snippet thresholdPanel(filter: TableFilterDropdownProps)} {@const draft = filter.selectedKeys[0]} <Flex vertical gap="small" style="padding: 12px"> <InputNumber aria-label={("Tarefa Mínimo")} min={0} precision={0} value={typeof draft === 'number' ? draft : null} onChange={value => filter.setSelectedKeys(typeof value === 'number' ? [value] : [])} /> <Flex gap="small" wrap> <Button size="small" type="primary" onclick={() => filter.confirm()}> {("Aplicar")} </Button> <Button size="small" onclick={() => filter.clearFilters({ confirm: true, closeDropdown: true })} > {("Redefinir")} </Button> </Flex> </Flex> {/snippet} <div class="filter-popup-host" bind:this={popupHost}> <Checkbox bind:checked={highlightOnly}> {("Selecione as correspondências e deixe todas as linhas")} </Checkbox> <Table aria-label={("Filtrar pelo número da tarefa")} dataSource={members} {columns} locale={{ filterTitle: ("Limite") }} getPopupContainer={trigger => popupHost ?? trigger.ownerDocument.body} onChange={acceptFilter} size="small" pagination={false} /> </div>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Comando | ||
|---|---|---|
| Глеб | Разработка | 24 |
| Анна | Разработка | 18 |
Filtros gerenciados
bind:sorter/filters Reinicialização e configuração do status do software.
Controlled.svelte<script lang="ts"> import { Button, Table, type TableFilters, type TableSorter } from '@woodger/antd'; import { filterColumns, members } from './data'; let sorter = $state<TableSorter | null>({ columnKey: 'tasks', order: 'descend' }); let filters = $state<TableFilters>({ team: ["Desenvolvimento"] }); </script> <style> .actions { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; } </style> <div class="actions"> <Button onclick={() => { sorter = null; filters = {}; }}> {("Reinicie os filtros e a classificação")} </Button> <Button onclick={() => { sorter = { columnKey: 'tasks', order: 'ascend' }; filters = { team: [ "Design" ] }; }}>{("Mostrar designers de tarefas")}</Button> </div> <Table dataSource={(members)} columns={(filterColumns)} caption={("Filtros de tabela gerenciada")} bind:sorter bind:filters pagination={(false)} />data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Nome | Comando | Tarefas |
|---|---|---|
| Анна | Разработка | 18 |
| Борис | Дизайн | 9 |
| Вера | Поддержка | 0 |
Tamanho e bordas
small/medium/large e bordered; Cabeçalho - caption.
Size.svelte<script lang="ts"> import { Checkbox, RadioGroup, Table, type ComponentSize } from '@woodger/antd'; import { columns, members } from './data'; let size = $state<ComponentSize>('medium'); let bordered = $state(true); </script> <style>.settings { display: flex; align-items: center; flex-wrap: wrap; gap: 16px; margin-bottom: 16px; }</style> <div class="settings" ><RadioGroup aria-label={("Tamanho da tabela")} bind:value={size} options={(['small', 'medium', 'large'])} /> <Checkbox bind:checked={bordered}>{("Limites da mesa")}</Checkbox></div> <Table dataSource={(members.slice(0, 3))} columns={(columns)} {size} {bordered} caption={("Tabela de tamanhos e limites")} pagination={(false)} />data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Nome | Comando | Tarefas |
|---|---|---|
| Участник 1 | Разработка | 18 |
| Участник 2 | Дизайн | 9 |
| Участник 3 | Поддержка | 0 |
| Участник 4 | Разработка | 24 |
| Участник 5 | Дизайн | 12 |
| Участник 6 | Поддержка | 15 |
| Участник 7 | Разработка | 18 |
| Участник 8 | Дизайн | 9 |
| Участник 9 | Поддержка | 0 |
| Участник 10 | Разработка | 24 |
| Участник 11 | Дизайн | 12 |
| Участник 12 | Поддержка | 15 |
| Участник 13 | Разработка | 18 |
| Участник 14 | Дизайн | 9 |
| Участник 15 | Поддержка | 0 |
| Участник 16 | Разработка | 24 |
| Участник 17 | Дизайн | 12 |
| Участник 18 | Поддержка | 15 |
| Участник 19 | Разработка | 18 |
| Участник 20 | Дизайн | 9 |
| Участник 21 | Поддержка | 0 |
| Участник 22 | Разработка | 24 |
| Участник 23 | Дизайн | 12 |
| Участник 24 | Поддержка | 15 |
Fixação e rolagem
interno scroll.y, horizontal scroll.x e fixed start/end.
Scroll.svelte<script lang="ts"> import { Checkbox, Table, type TableColumn } from '@woodger/antd'; import { members, type Member } from './data'; let fixed = $state(true); const rows = Array.from({ length: 24 }, (_, index) => ({ ...members[index % members.length], key: index, name: `Participante ${index + 1}` })); const columns = $derived<TableColumn<Member>[]>([ { key: 'name', title: "Nome", dataIndex: 'name', width: 180, fixed: fixed ? 'start' : false }, { key: 'team', title: "Comando", dataIndex: 'team', width: 480 }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', width: 120, fixed: fixed ? 'end' : false } ]); </script> <style>.settings { margin-bottom: 16px; }</style> <div class="settings" ><Checkbox bind:checked={fixed} >{("Proteja as colunas extremas")}</Checkbox></div> <Table dataSource={(rows)} columns={(columns)} caption={("Tabela de rolagem")} pagination={(false)} scroll={{ x: 900, y: 260 }} />data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
№ | Verifique | Tempo, com |
|---|---|---|
| 1 | Verificando links | 2 |
| 2 | Verifique o tipo | 3 |
| 3 | Amostra de verificação | 4 |
| 4 | Verificando links | 5 |
| 5 | Verifique o tipo | 6 |
| 6 | Amostra de verificação | 7 |
| 7 | Verificando links | 8 |
Virtual Scroll
Role por mil entradas ou navegue até a última com sua chave.
<script lang="ts">
import { Button, Flex, Table, type TableColumn, type TableRef } from '@woodger/antd';
interface CheckRun {
key: number;
title: string;
duration: number;
}
const runCount = 1_000;
const checks = ["Verificando links", "Verifique o tipo", "Amostra de verificação"];
const runs = Array.from({ length: runCount }, (_, index): CheckRun => ({
key: index + 1,
title: checks[index % checks.length],
duration: 2 + index % 30
}));
const columns: TableColumn<CheckRun>[] = [
{ key: 'run', title: '№', dataIndex: 'key', rowScope: 'row', width: 72, fixed: 'start' },
{ key: 'check', title: "Verifique", dataIndex: 'title', width: 280 },
{ key: 'duration', title: "Tempo, com", dataIndex: 'duration', width: 128, align: 'right' }
];
let table = $state<TableRef>();
let scrolled = $state(false);
</script>
<Flex vertical gap="medium">
<Flex gap="small" wrap>
<Button disabled={!scrolled} onclick={() => table?.scrollTo({ top: 0 })}>
{("Topo da tabela")}
</Button>
<Button onclick={() => table?.scrollTo({ key: runCount, align: 'end' })}>
{("até a última entrada")}
</Button>
</Flex>
<Table
bind:this={table}
aria-label={("Registro de verificação")}
columns={(columns)}
dataSource={(runs)}
virtual
size="small"
scroll={{ x: 480, y: 230 }}
onScroll={event => { scrolled = event.currentTarget.scrollTop > 0; }}
pagination={false}
/>
</Flex>
№ | Verifique |
|---|
- 1Verificando links
- 2Verifique o tipo
- 3Amostra de verificação
- 4Verificando links
- 5Verifique o tipo
- 6Amostra de verificação
- 7Verificando links
- 8Verifique o tipo
- 9Amostra de verificação
- 10Verificando links
- 11Verifique o tipo
- 12Amostra de verificação
- 13Verificando links
- 14Verifique o tipo
- 15Amostra de verificação
- 16Verificando links
- 17Verifique o tipo
- 18Amostra de verificação
- 19Verificando links
- 20Verifique o tipo
- 21Amostra de verificação
- 22Verificando links
- 23Verifique o tipo
- 24Amostra de verificação
Lista com sua rolagem
Cabeçalho e transição de chaves trabalham com a lista em sua própria área.
<script lang="ts">
import { Button, ConfigProvider, Flex, Table, type TableBodyRenderInfo, type TableColumn }
from '@woodger/antd';
import type { TableRef } from '@woodger/antd';
interface Check {
id: number;
title: string;
}
const firstColumnWidth = 72;
const width = 480;
const height = 168;
const lastCheck = 24;
const kinds = ["Verificando links", "Verifique o tipo", "Amostra de verificação"];
const checks = Array.from({ length: lastCheck }, (_, index): Check => ({
id: index + 1, title: kinds[index % kinds.length]
}));
const columns: TableColumn<Check>[] = [
{ key: 'id', title: '№', dataIndex: 'id', width: firstColumnWidth },
{ key: 'title', title: "Verifique", dataIndex: 'title', width: width - firstColumnWidth }
];
let table = $state<TableRef>();
</script>
{#snippet checksBody(records: readonly Check[], info: TableBodyRenderInfo)}
<div
role="region"
aria-label={("Lista de verificação")}
tabindex="0"
class="check-scroll"
style:block-size={`${height}px`}
{@attach info.ref}
onscroll={info.onScroll}
>
<ol
style:inline-size={`${width}px`}
style:--number-width={`${firstColumnWidth}px`}
>
{#each records as check (check.id)}
<li data-row-key={check.id}>
<span>{check.id}</span><span>{check.title}</span>
</li>
{/each}
</ol>
</div>
{/snippet}
<Flex vertical gap="medium">
<div>
<Button onclick={() => table?.scrollTo({ key: lastCheck, align: 'end' })}>
{("até a última entrada")}
</Button>
</div>
<ConfigProvider table={{ rowKey: 'id', scroll: { x: width, y: height } }}>
<Table
aria-label={("Verifique o registro com rolagem separada")}
dataSource={(checks)}
columns={(columns)}
components={{ body: checksBody }}
bind:this={table}
size="small"
pagination={false}
/>
</ConfigProvider>
</Flex>
<style>
.check-scroll { overflow: auto; }
ol {
list-style: none;
padding: 0;
margin: 0;
}
li {
display: grid;
grid-template-columns: var(--number-width) 1fr;
padding-block: 8px;
border-block-end: 1px solid var(--ant-color-border-secondary);
}
li span { padding-inline: 8px; }
</style>
Comando | ||
|---|---|---|
| Анна | Разработка | 18 |
| Борис | Дизайн | 9 |
| Вера | Поддержка | 0 |
| Глеб | Разработка | 24 |
| Дарья | Дизайн | 12 |
| Егор | Поддержка | 15 |
Composição da coluna
column.hidden Oculta as células, mantendo a classificação e os filtros.
Columns.svelte<script lang="ts"> import { Checkbox, Table } from '@woodger/antd'; import { filterColumns, members } from './data'; let tasks = $state(true); const columns = $derived(filterColumns.map(column => ({ ...column, hidden: column.key === 'tasks' && !tasks }))); </script> <style>.settings { margin-bottom: 16px; }</style> <div class="settings" ><Checkbox bind:checked={tasks} >{("Mostrar coluna de tarefa")}</Checkbox></div> <Table dataSource={(members)} columns={(columns)} caption={("A composição das colunas da tabela")} pagination={(false)} />data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Fornecedor | Atribuição de aplicação | Quantidade |
|---|---|---|
| Northern Machine-building Enterprise | Peças sobressalentes para manutenção programada de equipamentos Peças sobressalentes para manutenção programada de equipamentos | 12 |
| Leste | Kits de montagem em estação de trabalho Kits de montagem em estação de trabalho | 8 |
Largura da coluna e texto longo
Troque o algoritmo de largura. Aponte para a atribuição do aplicativo para o texto completo.
<script lang="ts">
import { Checkbox, Flex, Table, Tooltip, type TableColumnInput } from '@woodger/antd';
interface Request {
key: number;
supplier: { title: string };
title: string;
quantity: number;
}
const requests: Request[] = [
{
key: 1,
supplier: { title: "Northern Machine-building Enterprise" },
title: "Peças sobressalentes para manutenção programada de equipamentos",
quantity: 12
},
{
key: 2,
supplier: { title: "Leste" },
title: "Kits de montagem em estação de trabalho",
quantity: 8
}
];
const columns: TableColumnInput<Request>[] = [
{ title: "Fornecedor", dataIndex: ['supplier', 'title'], ellipsis: true },
{
key: 0, title: "Atribuição de aplicação", dataIndex: 'title', width: 172,
ellipsis: { showTitle: false }, render: requestTitle
},
{ title: "Quantidade", dataIndex: 'quantity', align: 'end', width: 86 }
];
let fixedLayout = $state(true);
</script>
{#snippet requestTitle(_request: Request, _index: number, value?: unknown)}
{#if typeof value === 'string'}
<Tooltip title={value} trigger={['hover', 'focus']}>
<span class="request-title" tabindex="0">{value}</span>
</Tooltip>
{/if}
{/snippet}
<Flex vertical gap="medium">
<Checkbox bind:checked={fixedLayout}>{("Largura da coluna fixa")}</Checkbox>
<Table
aria-label={("Solicitações de aquisição")}
dataSource={(requests)}
columns={(columns)}
column={{ align: 'start', width: 128, minWidth: 116 }}
tableLayout={fixedLayout ? 'fixed' : 'auto'}
scroll={{ x: 386 }}
pagination={false}
/>
</Flex>
<style>
.request-title {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
</style>
Participante | Carga de trabalho | |
|---|---|---|
Comando | Tarefas | |
| Anna | Desenvolvimento | 18 |
| Boris | Design | 9 |
| fé | Suporte | 0 |
| GLEB | Desenvolvimento | 24 |
| Daria | Design | 12 |
| egor | Suporte | 15 |
Grupos e visibilidade das colunas
Table.ColumnGroup Combina as colunas “Equipe” e “Tarefas”. Table.Column com a configuração responsive Mostra a coluna “acesso” de md.
GroupedColumns.svelte<script lang="ts"> import { Table } from '@woodger/antd'; import { members, type Member } from './data'; </script> {#snippet name(member: Member)} {(member.name)} {/snippet} {#snippet team(member: Member)} {(member.team)} {/snippet} {#snippet access(member: Member)} {member.active ? ("Abrir") : ("Suspendido")} {/snippet} <Table aria-label={("Carga do participante")} dataSource={members} onHeaderRow={(_, level) => ({ 'data-header-level': level })} size="small" bordered pagination={false} > <Table.Column key="name" title={("Participante")} rowScope="row" render={name} /> <Table.ColumnGroup key="work" title={("Carga de trabalho")}> <Table.Column key="team" title={("Comando")} render={team} /> <Table.Column key="tasks" title={("Tarefas")} dataIndex="tasks" align="right" /> </Table.ColumnGroup> <Table.Column key="access" title={("Acesso")} render={access} responsive={['md']} /> </Table>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Seção e Tarefa | Status | |
|---|---|---|
| Documentação | Verifique os links | Concluído |
| Manual de atualização | Executar | |
| Pacote | Colete o pacote | Concluído |
| Após as verificações publicar o problema. | ||
Células conjuntas
A seção ocupa várias linhas, e a nota - toda a largura da tabela.
<script lang="ts">
import { Table, type TableColumn } from '@woodger/antd';
interface ChecklistItem {
key: string;
section: string;
title: string;
sectionRows: number;
ready?: boolean;
note?: boolean;
}
const items: ChecklistItem[] = [
{
key: 'links', section: "Documentação", title: "Verifique os links", sectionRows: 2, ready: true
},
{
key: 'guide', section: "Documentação", title: "Manual de atualização", sectionRows: 0
},
{ key: 'build', section: "Pacote", title: "Colete o pacote", sectionRows: 1, ready: true },
{
key: 'note', section: "Após as verificações publicar o problema.", title: '',
sectionRows: 1, note: true
}
];
const columns: TableColumn<ChecklistItem>[] = [
{
key: 'section',
title: "Seção e Tarefa",
rowScope: 'row',
render: section,
onHeaderCell: () => ({ colSpan: 2 }),
onCell: item => ({ rowSpan: item.sectionRows, colSpan: item.note ? 3 : 1 })
},
{
key: 'task', title: "Tarefa de lançamento", dataIndex: 'title', colSpan: 0,
onCell: item => ({ colSpan: item.note ? 0 : 1 })
},
{
key: 'status', title: "Status", render: status,
onCell: item => ({ colSpan: item.note ? 0 : 1 })
}
];
</script>
{#snippet section(item: ChecklistItem)}
{(item.section)}
{/snippet}
{#snippet status(item: ChecklistItem)}
{item.ready ? ("Concluído") : ("Executar")}
{/snippet}
<Table
aria-label={("Verificações de lançamento")}
columns={(columns)}
dataSource={(items)}
onRow={item => ({ 'data-check': item.key })}
bordered
size="small"
pagination={false}
/>
Nome | Tarefas | Ação |
|---|---|---|
| Анна | 18 | |
| Борис | 9 | |
| Вера | 0 |
Editando a edição de células
A célula numérica recebe a entrada novamente quando o número de tarefas muda.
Editable.svelte<script lang="ts"> import { Button, InputNumber, Table, type TableColumn } from '@woodger/antd'; import { members, type Member } from './data'; let rows = $state(members.map(row => ({ ...row }))); let editing = $state<number | null>(null); let draft = $state<number | null>(null); let result = $state(''); const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'tasks', title: "Tarefas", render: tasks, shouldCellUpdate: (row, previous) => row.tasks !== previous.tasks }, { key: 'action', title: "Ação", render: action } ]; function save(row: Member) { if (draft === null) { return; } const tasks = draft; rows = rows.map(item => item.key === row.key ? { ...item, tasks } : item); result = ("" + String((row.name)) + ": " + String((tasks)) + ""); editing = null; } </script> <style> .actions { display: flex; flex-wrap: wrap; gap: 8px; } output { display: block; margin-top: 16px; } </style> {#snippet tasks(row: Member)} {#if editing === row.key}<InputNumber aria-label={("Tarefas do participante " + String((row.name)) + "")} bind:value={draft} min={0} precision={0} style="width: 88px" /> {:else}{(row.tasks)}{/if} {/snippet} {#snippet action(row: Member)} <div class="actions" >{#if editing === row.key}<Button size="small" disabled={draft === null} onclick={() => save(row)} >{("Salvar ")}{row.name}</Button> <Button size="small" onclick={() => { editing = null; }} >{("Cancelar ")}{row.name}</Button> {:else}<Button size="small" disabled={editing !== null} onclick={() => { editing = row.key; draft = row.tasks; }}>{("Editar ")}{row.name}</Button>{/if}</div> {/snippet} <Table dataSource={(rows.slice(0, 3))} columns={(columns)} caption={("Tabela de edição")} pagination={(false)} scroll={{ x: 460 }} /> <output aria-label={("Tabela de células salvas")}>{(result || '—')}</output>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Nome | Comando | Tarefas | |
|---|---|---|---|
| Анна | Разработка | 18 | |
| Борис | Дизайн | 9 | |
| Вера | Поддержка | 0 | |
Mesa aninhada
Separe uma tabela com as tarefas do participante dentro da linha aberta.
Nested.svelte<script lang="ts"> import { Table, type TableColumn } from '@woodger/antd'; import { columns, members, type Member } from './data'; interface Task { key: number; title: string; } const tasks: TableColumn<Task>[] = [{ key: 'title', title: "Nome da tarefa", dataIndex: 'title' }]; </script> {#snippet details(row: Member)} <Table dataSource={([{ key: 1, title: `Verifique os componentes: ${row.name}` }])} columns={(tasks)} caption={("Tarefas: " + String((row.name)) + "")} pagination={(false)} size="small" /> {/snippet} <Table dataSource={(members.slice(0, 3))} columns={(columns)} caption={("Tabelas aninhadas")} expandable={{ expandedRowRender: details, defaultExpandedRowKeys: [1] }} pagination={(false)} />data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Nome | Comando | Tarefas |
|---|---|---|
Ainda não há participantes nesta tabela | ||
Esvazie os dados e baixe
Local vazio local e indicador de carga atrasada.
Empty.svelte<script lang="ts"> import { Button, Checkbox, Empty, Table } from '@woodger/antd'; import { columns, members } from './data'; let loaded = $state(false); let loading = $state(false); const dataSource = $derived.by(() => { if (loaded) { return members; } return loading ? undefined : []; }); </script> <style>.settings { margin-bottom: 16px; }</style> {#snippet empty()}<Empty description={("Ainda não há participantes nesta tabela")} ><Button style=" max-width: 100%; height: auto; white-space: normal; " onclick={() => { loaded = true; }} >{("Adicionar strings demo")}</Button></Empty>{/snippet} <div class="settings" ><Checkbox bind:checked={loading} >{("Mesa vazia carregando")}</Checkbox></div> <Table dataSource={(dataSource)} columns={(columns)} locale={{ emptyText: empty }} loading={{ spinning: loading, delay: 150, description: ("Carga do participante") }} caption={("Tabela vazia")} pagination={(false)} />data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Nome | Comando | Tarefas |
|---|---|---|
| Анна | Разработка | 18 |
| Борис | Дизайн | 9 |
| Вера | Поддержка | 0 |
Paginação
Adicione a navegação acima da tabela e troque a página de ambos os lados.
Pagination.svelte<script lang="ts"> import { Checkbox, Table } from '@woodger/antd'; import { columns, members } from './data'; let current = $state(1); let pageSize = $state(3); let showTop = $state(false); </script> <style> .placement-control { margin-bottom: 16px; } output { display: block; margin-top: 16px; } </style> {#snippet total(count: number, range: [number, number])}{(range[0])}–{(range[1])}{(" de ")}{(count)}{/snippet} <div class="placement-control"> <Checkbox bind:checked={showTop}>{("Navegação sobre Tabela")}</Checkbox> </div> <Table dataSource={(members)} columns={(columns)} caption={("Tabela de paginação")} bind:current bind:pageSize pagination={({ 'aria-label': "Páginas de exemplo de paginação", placement: showTop ? ['topEnd', 'bottomEnd'] : ['bottomEnd'], showSizeChanger: true, pageSizeOptions: [3, 6], hideOnSinglePage: false, showTotal: total })} /> <output aria-label={("Tabela de página")}>{("Página: ")}{current}{("; Linhas: ")}{pageSize}</output>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Comando | Status | |||
|---|---|---|---|---|
Sem dados | ||||
Total: 0. Página: 1. Selecionado: 0.
Modo de servidor
Instantâneo query, cancelando solicitação desatualizada, erro e repetição. Os dados são simulados localmente.
RemoteTableExample.svelte<script lang="ts"> import { onMount } from 'svelte'; import { Alert, Button, Checkbox, Table, type TableColumn, type TableKey } from '@woodger/antd'; import { createRemoteTable } from './remote-table.model.svelte'; import { createMemberSource, remoteTeams, type RemoteMember } from './remote-members'; const source = createMemberSource(); const remote = createRemoteTable(source.load); let selected = $state<TableKey[]>([]); let fixed = $state(true); let columns = $derived<TableColumn<RemoteMember>[]>([ { key: 'name', title: "Participante", dataIndex: 'name', sorter: true, width: 200, fixed }, { key: 'team', title: "Comando", dataIndex: 'team', width: 220, filters: remoteTeams.map((team) => ({ text: team, value: team })) }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', width: 160, sorter: true }, { key: 'active', title: "Status", render: memberStatus, width: 160, fixed: fixed ? 'end' : false, filterMultiple: false, filters: [{ text: "Ativo", value: true }, { text: "Suspendido", value: false }] } ]); onMount(() => { void remote.load(); return remote.dispose; }); function showError() { source.failNextRequest(); void remote.load(); } </script> <style> .actions { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; margin-bottom: 20px; } .remote-status { margin: 16px 0 0; color: var(--ant-color-text-tertiary); font-size: 12px; } .error { margin-bottom: 16px; } .active { color: var(--ant-color-success); } </style> {#snippet memberStatus(member: RemoteMember)}<span class:active={member.active}>{(member.active ? "Ativo" : "Suspendido")}</span>{/snippet} {#snippet retry()}<Button type="primary" onclick={remote.retry} >{("Repita o download")}</Button>{/snippet} <div class="actions"><Button onclick={() => { void remote.load(); }}> {("Atualização")} </Button><Button onclick={showError} >{("Exemplo de erro de download")}</Button><Checkbox bind:checked={fixed} >{("Cabeçalho e colunas seguras")}</Checkbox></div> {#if remote.error}<div class="error"><Alert type="error" title={(remote.error)} action={retry} showIcon /></div>{/if} <Table mode="server" total={remote.total} dataSource={(remote.rows)} columns={(columns)} caption={("Membros remotos")} bind:current={remote.current} bind:pageSize={remote.pageSize} bind:sorter={remote.sorter} bind:filters={remote.filters} bind:selectedRowKeys={selected} rowSelection={{ fixed, getCheckboxProps: (member) => ({ disabled: !member.active, 'aria-label': `Selecione o membro remoto ${member.key}` }) }} loading={remote.loading} onChange={remote.change} pagination={({ showSizeChanger: true, pageSizeOptions: [5, 10, 20], 'aria-label': "Páginas de membros remotos" })} scroll={{ x: 900, y: fixed ? 300 : undefined }} /> <p class="remote-status" role="status" aria-label={("Resultado do download remoto")} >{("Total: ")}{(remote.total)}{(". Página: ")}{(remote.current)}{(". Selecionado: ")}{(selected.length)}.</p>remote-table.model.svelte.tsimport type { TableChange, TableFilters, TableSorter } from '@woodger/antd'; import { getPaginationState } from '@woodger/antd'; export interface RemoteTableQuery { current: number; pageSize: number; sorter: TableSorter | null; filters: TableFilters; } export interface RemoteTablePage<Row extends object> { rows: readonly Row[]; total: number; } export type RemoteTableLoader<Row extends object> = ( query: RemoteTableQuery, signal: AbortSignal ) => Promise<RemoteTablePage<Row>>; function copyQuery(query: RemoteTableQuery): RemoteTableQuery { return { current: query.current, pageSize: query.pageSize, sorter: query.sorter ? { ...query.sorter } : null, filters: Object.fromEntries( Object.entries(query.filters).map(([key, values]) => [key, [...values]]) ) }; } export function createRemoteTable<Row extends object>( loadPage: RemoteTableLoader<Row>, initial: Partial<RemoteTableQuery> = {} ) { let current = $state(initial.current ?? 1); let pageSize = $state(initial.pageSize ?? 5); let sorter = $state<TableSorter | null>(initial.sorter ? { ...initial.sorter } : null); let filters = $state<TableFilters>( Object.fromEntries( Object.entries(initial.filters ?? {}).map(([key, values]) => [key, [...values]]) ) ); let rows = $state.raw<readonly Row[]>([]); let total = $state(0); let loading = $state(false); let error = $state<string | null>(null); let requestId = 0; let controller: AbortController | undefined; let disposed = false; let lastQuery = readQuery(); function readQuery(): RemoteTableQuery { return copyQuery({ current, pageSize, sorter, filters }); } async function load(query: RemoteTableQuery = readQuery()) { if (disposed) { return; } const id = ++requestId; controller?.abort(); const activeController = new AbortController(); controller = activeController; let pending = copyQuery(query); lastQuery = copyQuery(pending); current = pending.current; pageSize = pending.pageSize; sorter = pending.sorter ? { ...pending.sorter } : null; filters = copyQuery(pending).filters; rows = []; error = null; loading = true; try { while (true) { const page = await loadPage(copyQuery(pending), activeController.signal); if (disposed || id !== requestId) { return; } const paging = getPaginationState(page.total, pending.current, pending.pageSize); total = paging.total; current = paging.current; pageSize = paging.pageSize; if (pending.current !== paging.current || pending.pageSize !== paging.pageSize) { pending = { ...pending, current: paging.current, pageSize: paging.pageSize }; lastQuery = copyQuery(pending); continue; } rows = [...page.rows]; return; } } catch { if (!disposed && id === requestId) { error = "Não é possível carregar os dados. tente novamente."; } } finally { if (!disposed && id === requestId) { loading = false; controller = undefined; } } } return { get current() { return current; }, set current(value: number) { current = value; }, get pageSize() { return pageSize; }, set pageSize(value: number) { pageSize = value; }, get sorter() { return sorter; }, set sorter(value: TableSorter | null) { sorter = value; }, get filters() { return filters; }, set filters(value: TableFilters) { filters = value; }, get rows() { return rows; }, get total() { return total; }, get loading() { return loading; }, get error() { return error; }, get query() { return readQuery(); }, load, retry() { return load(lastQuery); }, change(change: TableChange<Row>) { return load( { current: change.pagination.current, pageSize: change.pagination.pageSize, sorter: change.sorter, filters: change.filters ?? {} } ); }, dispose() { disposed = true; requestId++; controller?.abort(); controller = undefined; loading = false; } }; }remote-members.tsimport type { TableColumn } from '@woodger/antd'; import { getTableData } from '@woodger/antd'; import type { RemoteTableLoader } from './remote-table.model.svelte'; export interface RemoteMember { key: number; name: string; team: string; tasks: number; active: boolean; } export const remoteTeams = ["Desenvolvimento", "Design", "Suporte"]; export function createMemberSource() { let failNext = false; const members: RemoteMember[] = Array.from({ length: 36 }, (_, index) => ({ key: index + 1, name: `Participante ${String(index + 1).padStart(2, '0')}`, team: remoteTeams[index % remoteTeams.length], tasks: index * 7 % 43, active: index % 5 !== 1 })); const columns: TableColumn<RemoteMember>[] = [ { key: 'name', title: "Participante", sorter: (left, right) => left.name.localeCompare(right.name, 'ru') }, { key: 'team', title: "Comando", filters: remoteTeams.map((team) => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", sorter: (left, right) => left.tasks - right.tasks }, { key: 'active', title: "Status", filters: [{ text: "Ativo", value: true }, { text: "Suspendido", value: false }], onFilter: (value, row) => row.active === value } ]; const load: RemoteTableLoader<RemoteMember> = (query, signal) => { const fail = failNext; failNext = false; return new Promise((resolve, reject) => { signal.throwIfAborted(); const timer = setTimeout(() => { signal.removeEventListener('abort', cancel); if (fail) { reject(new Error('Demo request failed')); return; } const data = getTableData(members, columns, undefined, query.sorter, query.filters); const start = (query.current - 1) * query.pageSize; resolve( { rows: data.rows.slice(start, start + query.pageSize).map((row) => row.record), total: data.rows.length } ); }, 350); function cancel() { clearTimeout(timer); signal.removeEventListener('abort', cancel); reject(signal.reason); } signal.addEventListener('abort', cancel, { once: true }); }); }; return { load, failNextRequest() { failNext = true; } }; }
Participante | Comando | Tarefas | ||
|---|---|---|---|---|
| Марина Белова | Разработка | 18 | ||
| Павел Громов | Дизайн | 9 | ||
| Нина Романова | Поддержка | 0 | ||
Divulgado: 1. Selecionado: 0.
Linhas desabilitadas
Detalhes, rowExpandable, seleção e economia expandable.expandedRowKeys entre as páginas. O proprietário atualiza as chaves via expandable.onExpandedRowsChange.
<script lang="ts">
import { Button, Table, type TableColumn, type TableKey } from '@woodger/antd';
interface Member {
key: number;
name: string;
team: string;
email: string;
tasks: number;
active: boolean
}
const members: Member[] = [
{
key: 1,
name: "Marina Belova",
team: "Desenvolvimento",
email: 'marina@example.com',
tasks: 18,
active: true
},
{
key: 2,
name: "Pavel Gromov",
team: "Design",
email: 'pavel@example.com',
tasks: 9,
active: true
},
{
key: 3,
name: "Nina Romanova",
team: "Suporte",
email: 'nina@example.com',
tasks: 0,
active: false
},
{
key: 4,
name: "Oleg Krylov",
team: "Desenvolvimento",
email: 'oleg@example.com',
tasks: 24,
active: true
},
{
key: 5,
name: "Svetlana Morozova",
team: "Design",
email: 'svetlana@example.com',
tasks: 12,
active: true
},
{
key: 6,
name: "Timur Zaitsev",
team: "Suporte",
email: 'timur@example.com',
tasks: 15,
active: true
}
];
const columns: TableColumn<Member>[] = [
{ key: 'name', title: "Participante", dataIndex: 'name', width: 220, fixed: true },
{ key: 'team', title: "Comando", dataIndex: 'team', width: 360 },
{
key: 'tasks',
title: "Tarefas",
dataIndex: 'tasks',
width: 120,
align: 'right',
fixed: 'end'
}
];
let expanded = $state<TableKey[]>([1]);
let selected = $state<TableKey[]>([]);
let current = $state(1);
let pageSize = $state(3);
</script>
<style>
.actions { margin-bottom: 20px; }
.details {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
gap: 16px;
margin: 0;
}
.details > div { min-width: 0; }
dt {
margin-bottom: 4px;
color: var(--ant-color-text-tertiary);
font-size: 12px;
}
dd { margin: 0; }
.state {
margin: 16px 0 0;
color: var(--ant-color-text-tertiary);
font-size: 12px;
}
</style>
{#snippet details(member: Member)}
<dl class="details" aria-label={("Detalhes do participante " + String((member.key)) + "")}>
<div><dt>{("Participante")}</dt><dd>{member.name}</dd></div>
<div><dt>Email</dt><dd>{member.email}</dd></div>
<div><dt>{("Comando")}</dt><dd>{(member.team)}</dd></div>
<div><dt>{("Abrir Tarefas")}</dt><dd>{(member.tasks)}</dd></div>
</dl>
{/snippet}
<div
class="actions"
><Button
onclick={() => { expanded = []; }}
disabled={!expanded.length}
>{("Recolher Todos os detalhes")}</Button></div>
<Table
dataSource={(members)}
columns={(columns)}
caption={("Cartões de Participantes")}
expandable={{
expandedRowRender: details,
rowExpandable: (member) => member.active,
fixed: true,
expandedRowKeys: expanded,
onExpandedRowsChange: keys => { expanded = keys; }
}}
rowSelection={{
fixed: true,
getCheckboxProps: (member) =>
({ disabled: !member.active, 'aria-label': `Selecione Cartão ${member.key}` })
}}
bind:selectedRowKeys={selected}
bind:current
bind:pageSize
pagination={({
'aria-label': "Páginas Cartões de Participantes",
showSizeChanger: true,
pageSizeOptions: [3, 6]
})}
scroll={{ x: 1000, y: 380 }}
/>
<p class="state" role="status" aria-label={("Divulgação de Cartões")}>{("Divulgado: ")}{(expanded.length)}{(". Selecionado: ")}{(selected.length)}.</p>
Participante | Nota | |
|---|---|---|
| Anna | Anna | |
| Boris | Boris | |
| fé | fé | |
Colunas de serviço e abrindo
Abra a nota, insira o texto e recorte a linha. O rascunho será salvo.
CustomDetails.svelte<script lang="ts"> import { Button, ConfigProvider, Input, Table, Tooltip, type TableColumn, type TableExpandIconInfo } from '@woodger/antd'; import type { Snippet } from 'svelte'; import { members, type Member } from './data'; const dataSource = members.slice(0, 3); const columns = $derived<TableColumn<Member>[]>([ { key: 'name', title: ("Participante"), rowScope: 'row', render: name }, Table.EXPAND_COLUMN, Table.SELECTION_COLUMN ]); </script> {#snippet name(member: Member)} {(member.name)} {/snippet} {#snippet expandIcon(info: TableExpandIconInfo)} {#if info.expandable} <Button type="link" size="small" disabled={info.disabled} aria-expanded={info.expanded} aria-controls={info.ariaControls} onclick={info.onExpand} > {info.expanded ? ("Ocultar nota") : ("Abrir nota")} </Button> {/if} {/snippet} {#snippet details(member: Member)} <Input name={`note-${member.key}`} aria-label={("Notas de rascunho")} placeholder={("Nota do participante")} /> {/snippet} {#snippet selectionCell(_checked: boolean, member: Member, _index: number, checkbox: Snippet)} <Tooltip title={(member.name)}> {@render checkbox()} </Tooltip> {/snippet} <ConfigProvider table={{ expandable: { expandIcon } }}> <Table aria-label={("Notas dos participantes")} {columns} {dataSource} expandable={{ expandedRowRender: details, columnTitle: ("Nota"), rowExpandable: member => member.active, forceRender: true, expandRowByClick: true }} rowSelection={{ columnWidth: 60, getCheckboxProps: member => ({ 'aria-label': (member.name) }), renderCell: selectionCell }} size="small" pagination={false} /> </ConfigProvider>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Comando | ||
|---|---|---|
| Анна | Разработка | 18 |
| Борис | Дизайн | 9 |
| Вера | Поддержка | 0 |
Painéis, Cabeçalhos e Linhas
title/footer Receba a página atual; showHeader, rowHoverable, rowClassName e rowScope.
Panels.svelte<script lang="ts"> import { Checkbox, Table } from '@woodger/antd'; import type { TableColumn } from '@woodger/antd'; import { filterColumns, members, type Member } from './data'; let showHeader = $state(true); let rowHoverable = $state(true); const columns: TableColumn<Member>[] = filterColumns.map( column => column.key === 'name' ? { ...column, rowScope: 'row', className: 'table-member-name' } : column ); </script> <style> .settings { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 24px; } .example :global(.table-member-name) { font-weight: 600; } .example :global(.table-inactive) { color: var(--ant-color-text-disabled); } </style> <div class="settings"> <Checkbox bind:checked={showHeader}>{("Tabela de cabeçalhos da tabela")}</Checkbox> <Checkbox bind:checked={rowHoverable}>{("Tabela de luz de fundo")}</Checkbox> </div> <div class="example"> <Table dataSource={(members)} columns={(columns)} {showHeader} {rowHoverable} rowClassName={record => record.active ? '' : 'table-inactive'} defaultPageSize={3} > {#snippet caption()} <strong>{("Painéis e linhas Tabela")}</strong> {/snippet} {#snippet title(rows: readonly Member[])} <span role="status" aria-label={("Tabela da página atual")}>{rows.map( row => row.name ).join(', ')}</span> {/snippet} {#snippet footer(rows: readonly Member[])} <span role="status" aria-label={("Página ⟨ Tabela de resultados")}>{("Tarefas por página: ")}{(rows.reduce( ( sum, row ) => sum + row.tasks, 0 ))}</span> {/snippet} </Table> </div>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Participante | Comando | Tarefas |
|---|---|---|
| Anna | Desenvolvimento | 18 |
| Boris | Design | 9 |
| fé | Suporte | 0 |
| Total de Tarefas na página | 27 | |
Corrigindo o cabeçalho e os totais
Role pelo relatório dentro do cartão. O resultado muda com a página.
SummarySticky.svelte<script lang="ts"> import { Table, type TableColumn } from '@woodger/antd'; import { members, type Member } from './data'; const columns: TableColumn<Member>[] = [ { key: 'name', title: "Participante", render: name, width: 144 }, { key: 'team', title: "Comando", render: team, width: 252 }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', width: 114 } ]; let report = $state<HTMLDivElement>(); </script> {#snippet name(member: Member)} {(member.name)} {/snippet} {#snippet team(member: Member)} {(member.team)} {/snippet} {#snippet summary(page: readonly Member[])} {@const taskCount = page.reduce((sum, member) => sum + member.tasks, 0)} <Table.Summary> <Table.Summary.Row> <Table.Summary.Cell index={0} colSpan={2}> {("Total de Tarefas na página")} </Table.Summary.Cell> <Table.Summary.Cell index={2} align="end">{taskCount}</Table.Summary.Cell> </Table.Summary.Row> </Table.Summary> {/snippet} <div class="report-scroll" role="region" aria-label={("Relatório de rolagem")} tabindex="0" bind:this={report} > <Table aria-label={("Tarefas dos participantes")} columns={(columns)} dataSource={members} defaultPageSize={3} scroll={{ x: 510 }} sticky={{ getContainer: () => report }} summary={{ fixed: 'bottom', render: summary }} /> </div> <style> .report-scroll { max-block-size: 200px; overflow: auto; } </style>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Participante | Tarefas |
|---|---|
| Anna | 18 |
| Boris | 9 |
| fé | 0 |
| GLEB | 24 |
| Daria | 12 |
| egor | 15 |
Desenho de elementos de mesa
Compactie células através de styles e string com seu atributo HTML.
SemanticElements.svelte<script lang="ts"> import { Checkbox, ConfigProvider, Flex, Table, type TableColumn, type TableElementRenderInfo } from '@woodger/antd'; import { members, type Member } from './data'; const columns: TableColumn<Member>[] = [ { key: 'name', title: "Participante", rowScope: 'row', render: name }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'end' } ]; let compact = $state(false); </script> {#snippet name(member: Member)}{(member.name)}{/snippet} {#snippet workloadRow({ attributes, children, ref }: TableElementRenderInfo<'tr'>)} <tr {...attributes} data-workload-row="" {@attach ref}> {@render children()} </tr> {/snippet} <Flex vertical gap="medium"> <Checkbox bind:checked={compact}>{("Células compactas")}</Checkbox> <ConfigProvider table={{ classNames: { header: { cell: 'workload-heading' } } }}> <Table aria-label={("Design de carga de trabalho")} dataSource={members} columns={(columns)} components={{ body: { row: workloadRow } }} onRow={member => ({ 'data-unassigned': member.tasks === 0 ? '' : undefined })} styles={{ body: { cell: compact ? 'padding-block: 6px' : undefined } }} pagination={false} /> </ConfigProvider> </Flex> <style> :global(.workload-heading) { background: var(--ant-color-fill-tertiary); } tr[data-unassigned] { font-weight: 600; } </style>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
Comando | ||||
|---|---|---|---|---|
| Анна | Разработка | 18 | ||
| Борис | Дизайн | 9 | ||
| Вера | Поддержка | 0 |
Nome | Comando | Tarefas |
|---|---|---|
| Анна | Разработка | 18 |
Componente Tema
Caps, células e tokens footer, seleção de linha, tamanho, tema aninhado e RTL.
Theme.svelte<script lang="ts"> import { Checkbox, ConfigProvider, RadioGroup, Table } from '@woodger/antd'; import type { ComponentSize } from '@woodger/antd'; import { columns, filterColumns, members, type Member } from './data'; let enabled = $state(true); let size = $state<ComponentSize>('large'); </script> <style> .settings { display: grid; gap: 16px; margin-bottom: 24px; } .nested { margin-top: 24px; } </style> <div class="settings"> <Checkbox bind:checked={enabled}>{("Aplicar tabela de tokens")}</Checkbox> <RadioGroup aria-label={("Tamanho da mesa temática")} bind:value={size} options={(['large', 'medium', 'small'])} /> </div> <ConfigProvider direction="rtl" theme={{ components: { Table: enabled ? { headerBg: '#fff7e6', headerColor: '#874d00', cellPaddingBlock: 24, cellPaddingInline: 28, cellPaddingBlockMD: 22, cellPaddingInlineMD: 26, cellPaddingBlockSM: 8, cellPaddingInlineSM: 12, rowSelectedBg: '#fff1b8', rowExpandedBg: '#fffbe6', rowHoverBg: '#fff7e6', footerBg: '#fff7e6', footerColor: '#874d00', filterDropdownBg: '#fffbe6', selectionColumnWidth: 44 } : {} } }}> <Table dataSource={(members.slice(0, 3))} columns={(filterColumns)} {size} caption={("Tabela de temas do componente")} rowSelection defaultSelectedRowKeys={[1]} pagination={(false)} expandable={{ expandedRowRender: details }} > {#snippet footer(rows: readonly Member[])}{("Participantes: ")}{(rows.length)}{/snippet} </Table> <div class="nested"> <ConfigProvider theme={{ inherit: false, components: { Table: { headerBg: '#f6ffed', cellPaddingBlock: 6 } } }}> <Table dataSource={(members.slice(0, 1))} columns={(columns)} size="large" caption={("Tabela de temas isolados")} pagination={(false)} style="border-radius:14px" /> </ConfigProvider> </div> </ConfigProvider> {#snippet details(record: Member)}{("Detalhes do participante: ")}{record.name}{/snippet}data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
local prefixCls Especifica a tabela de nomes completos, dropdownPrefixCls — o nome da lista de filtros de base com o menu. A string vazia retorna o prefixo do provedor. O shell do filtro, caixa de seleção, paginação, botão e entrada de forma independente herdam o namespace comum. A mudança de nome salva a string aberta, editor, seleção, página e rascunho de filtro aberto; CSS As variáveis são definidas separadamente.
CSS Prefixos da tabela
Geral e local prefixCls, separar dropdownPrefixCls, rtl e CSS variáveis. O editor de strings abertos, a seleção, os filtros e a paginação são salvos ao alterar os nomes.
Prefix.svelte<script lang="ts"> import { Button, Checkbox, ConfigProvider, Input, Table, type TableColumn, type TableFilters, type TableKey, type TableSorter } from '@woodger/antd'; import { filterColumns, members, type Member } from './data'; let custom = $state(true); let local = $state(true); let localMenu = $state(true); let rtl = $state(false); let withVariables = $state(false); let selected = $state<TableKey[]>([1]); let expanded = $state<TableKey[]>([1]); let sorter = $state<TableSorter | null>(null); let filters = $state<TableFilters>({}); let current = $state(1); let events = $state<string[]>([]); let notes = $state<Record<string, string>>(Object.fromEntries( members.map(record => [String(record.key), `Nota: ${record.name}`]) )); let submitted = $state('—'); const prefix = $derived(custom ? 'suite' : 'ant'); const tablePrefix = $derived(local ? 'project-grid' : ''); const menuPrefix = $derived(localMenu ? 'project-filters' : ''); const columns: TableColumn<Member>[] = filterColumns.map(column => ({ ...column, width: column.key === 'team' ? 420 : 160, fixed: column.key === 'name' ? 'start' : undefined })); </script> <style> .example, form, .editor { display: grid; grid-template-columns: minmax(0, 1fr); gap: 16px; min-width: 0; } .controls { display: flex; flex-wrap: wrap; gap: 12px; } .editor { gap: 8px; } p { margin: 0; } output { overflow-wrap: anywhere; } </style> {#snippet details(record: Member)} <div class="editor"> <label for={`table-prefix-note-${record.key}`} >{("Nota do participante ")}{record.name}</label> <Input id={`table-prefix-note-${record.key}`} name={`note-${record.key}`} aria-label={("Rascunho das linhas " + String((record.name)) + "")} bind:value={notes[String( record.key )]} /> </div> {/snippet} <div class="example"> <div class="controls"> <Checkbox bind:checked={custom}>{("General Prefix Table Suite")}</Checkbox> <Checkbox bind:checked={local}>{("Tabela de prefixos locais")}</Checkbox> <Checkbox bind:checked={localMenu}>{("Tabela de menus da tabela de prefixos locais")}</Checkbox> <Checkbox bind:checked={rtl}>{("Tabela RTL com prefixo")}</Checkbox> <Checkbox bind:checked={withVariables}>CSS variables Table</Checkbox> </div> <ConfigProvider prefixCls={prefix} direction={rtl ? 'rtl' : 'ltr'} theme={withVariables ? { cssVar: { prefix: 'table-theme' } } : undefined}> <form aria-label={("tabela com prefixo")} onsubmit={event => { event.preventDefault(); submitted = Array.from(new FormData(event.currentTarget), ([name, value]) => `${name}: ${value}`).join('; ') || '—'; }}> <Table prefixCls={tablePrefix} dropdownPrefixCls={menuPrefix} class="prefix-table-main" dataSource={(members)} columns={(columns)} caption={("Tabela com prefixo CSS")} bind:selectedRowKeys={selected} bind:sorter bind:filters bind:current rowSelection={{ fixed: true, getCheckboxProps: record => ({ 'aria-label': `Selecione o membro com prefixo ${record.name}` }) }} expandable={{ expandedRowRender: details, expandedRowKeys: expanded, fixed: true, onExpandedRowsChange: keys => { expanded = keys; events.push('expand'); } }} defaultPageSize={3} pagination={({ showSizeChanger: false })} scroll={{ x: 900, y: 240 }} onChange={change => { events.push(change.action); }} onSelectionChange={() => { events.push('selection'); }} /> <div><Button htmlType="submit">{("Leia FormData Tabela")}</Button></div> <output aria-label={("FormData Tabela com prefixo")}>{submitted}</output> </form> </ConfigProvider> <output aria-label={("Estado da tabela com prefixo")}>{("\n Página: ")}{current}{("; Selecionado: ")}{(selected .join(', ') || '—')}{("; Divulgado: ")}{(expanded.join(', ') || '—')} </output> <output aria-label={("Eventos da tabela com prefixo")}>{(events.join(' | ') || ("Sem eventos"))}</output> <output aria-label={("CSS Tabela de prefixos")}> Table: {(tablePrefix || prefix + '-table')}{("; Lista de filtros: ")}{(menuPrefix || prefix + '-dropdown')}-menu </output> <p> {("local prefixCls Especifica a tabela de nomes completos, dropdownPrefixCls — o nome da lista de filtros de base com o menu. A string vazia retorna o prefixo do provedor. O shell do filtro, caixa de seleção, paginação, botão e entrada de forma independente herdam o namespace comum. A mudança de nome salva a string aberta, editor, seleção, página e rascunho de filtro aberto; CSS As variáveis são definidas separadamente.")} </p> </div>data.tsimport type { TableColumn } from '@woodger/antd'; export interface Member { key: number; name: string; team: string; tasks: number; active: boolean; } export const members: Member[] = [ { key: 1, name: "Anna", team: "Desenvolvimento", tasks: 18, active: true }, { key: 2, name: "Boris", team: "Design", tasks: 9, active: true }, { key: 3, name: "fé", team: "Suporte", tasks: 0, active: false }, { key: 4, name: "GLEB", team: "Desenvolvimento", tasks: 24, active: true }, { key: 5, name: "Daria", team: "Design", tasks: 12, active: true }, { key: 6, name: "egor", team: "Suporte", tasks: 15, active: true } ]; export const columns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name' }, { key: 'team', title: "Comando", dataIndex: 'team' }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right' } ]; export const filterColumns: TableColumn<Member>[] = [ { key: 'name', title: "Nome", dataIndex: 'name', sorter: (a, b) => a.name.localeCompare( b.name, 'ru' ) }, { key: 'team', title: "Comando", dataIndex: 'team', filters: ["Desenvolvimento", "Design", "Suporte"].map(team => ({ text: team, value: team })), onFilter: (value, row) => row.team === value }, { key: 'tasks', title: "Tarefas", dataIndex: 'tasks', align: 'right', sorter: ( a, b ) => a.tasks - b.tasks } ];
API
Os exemplos são baseados em Ant Design 6.6.8 e public API @woodger/antd.
| Tema | Exemplo ou restrição |
|---|---|
| Basic Usage | Digitado columns, dataSource e rowKey. |
| JSX style API | Table.Column e Table.ColumnGroup Declare colunas e grupos dentro da tabela. |
| selection | Seleção de um ou mais participantes com Radio e Checkbox. |
| Selection and operation | Ação do proprietário sobre selectedRowKeys. |
| Custom selection | Seleção do menu de todas as entradas, inversão de página e redefinição de marca. |
| Filter and sorter | Comparador e lista de filtros planos. |
| Filter in Tree | Filtro com opções divulgáveis. |
| Filter search | Procure opções via filterSearch. |
| Multiple sorter | Classifique por comando e, em seguida, por número de tarefas. |
| Reset filters and sorters | O status pertence ao proprietário. |
| Customized filter panel | trecho de painel com limite numérico e seu próprio ícone. |
| Ajax | mode=server com total; A fonte local demonstra a consulta, o cancelamento, o erro e a repetição. |
| size | small/medium/large; Herança componentSize. |
| border, title and footer | bordered, caption e Snippets title/footer com os dados da página atual. |
| Expandable Row | expandedRowRender e rowExpandable. |
| Expand all rows | No exemplo, a divulgação controla o aplicativo. defaultExpandAllRows Define o início. |
| Order Specific Column | Marcadores Table.EXPAND_COLUMN e Table.SELECTION_COLUMN Definir ordem. |
| colSpan and rowSpan | O cabeçalho e as células de dados ocupam várias linhas ou colunas. |
| Tree data | Entradas aninhadas por meio de children e seleção de linha associada. |
| Fixed Header | O cabeçalho é fixo dentro de scroll.y. |
| Auto height | Não há cálculo automático de altura da janela. |
| Fixed Columns | fixed true/start/end numérico width e rolagem horizontal. |
| Stack Fixed Columns | A correção sequencial não foi movida. |
| Fixed Columns and Header | Colaboração scroll.x/y e fixed. |
| Hidden Columns | column.hidden Remove as células do DOM, mantendo a classificação e os filtros de coluna. |
| Grouping table head | Colunas filhas em children formam um cabeçalho de vários níveis. |
| Editable Cells | Snippet e InputNumber, o estado de edição pertence ao exemplo. |
| Editable Rows | Mostra a salvação do registro pelo proprietário; onRow/components e nenhuma string editável integrada. |
| Nested tables | Tabela de composição dentro expandedRowRender. |
| Drag sorting | As strings de arrastar e soltar não são integradas. |
| Drag Column sorting | Sem colunas de arrastar e soltar. |
| Drag sorting with handler | Sem manipulador/components Para arrastar e soltar. |
| ellipsis column | Cortando o texto em uma coluna com uma dada largura. |
| Shared column props | Largura geral e alinhamento via propriedade column. |
| ellipsis column custom tooltip | Trim embutido e Tooltip com texto completo. |
| Custom empty | Snippet vazio e RenderEmpty de ConfigProvider. |
| Summary | Table.Summary Exibe os resultados das entradas da página atual. |
| Virtual list | Janela de linhas visíveis e faça a transição para a entrada selecionada por meio de scrollTo. |
| Responsive | responsive Controla a visibilidade dos colunas em diferentes larguras de tela. |
| Pagination Settings | Navegação superior e inferior via pagination.placement. |
| Fixed header and scroll bar with the page | sticky Corrige o cabeçalho e a barra de rolagem em uma determinada área. |
| Dynamic Settings | Tamanho/configurações de limite disponíveis mais separados loading, scroll, exemplos de seleção. |
| Custom semantic dom styling | Classes da tampa e estilos de células através de classNames e styles. |
| Custom body | Seu corpo está associado ao título e ao método scrollTo. |
| Conditional cell updates | Editor com shouldCellUpdate Atualizações de software. |
Table
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
prefixCls | Tabela de nomes local completo, incluindo wrapper, linhas, células e elementos filtrantes. String vazio/undefined Selecione ConfigProvider. Os controles aninhados mantêm um prefixo comum independente. | string | Prefixo geral + -Tabela |
dropdownPrefixCls | Nome da lista de filtros: adicionado -menu. Não altera o prefixo geral do shell popup, Checkbox e Button; Empty String/undefined Retorna o prefixo comum. | string | Prefixo geral + -dropdown |
dataSource | Dados da tabela. Um array vazio denota um resultado vazio conhecido. | readonly Row[] | null | — |
columns | Matriz de colunas e grupos. Se columns for fornecido, terá precedência sobre as declarações aninhadas. | readonly TableColumnInput<Row>[] | — |
column | Preencha a coluna ausente e as propriedades do grupo. | TableColumnDefaults<Row> | — |
getPopupContainer | Filtro de contêiner e menu de comando de seleção. | (trigger: HTMLElement) => HTMLElement | de ConfigProvider |
rowKey | Campo de registro ou função que retorna sua chave exclusiva estável. | keyof Row | (record) => string | number | ConfigProvider.table.rowKey / key |
mode | No servidor, a filtragem local, a classificação e a fatia são desativadas. | client | server | client |
total | Número total de entradas do servidor; No cliente, ele é calculado após os filtros. | number | dataSource.length no servidor |
sorter | bind:sorter, um tipo. | TableSorter | null | Estado local |
defaultSorter | Classificação inicial. | TableSorter | null | null |
sortDirections | Alternando a ordem das direções de classificação. | readonly (TableSortOrder | null)[] | ascend, descend |
showSorterTooltip | Dica no ícone de título ou classificação. | boolean | TableSorterTooltipProps | true |
filters | bind:filters; Tecla de coluna → Matriz de valores selecionados. | TableFilters | Estado local |
defaultFilters | Filtros iniciais. | Readonly<Record<string, readonly TableFilterValue[]>> | {} |
current | bind:current - Página da unidade. | number | Estado local |
defaultCurrent | Página inicial. | number | 1 |
pageSize | bind:pageSize — Tamanho da página. | number | Estado local |
defaultPageSize | Inicie o número de linhas. | number | 10 |
pagination | Configurações Pagination incluindo um ou dois pagers. | false | TablePaginationConfig | Ativado |
rowSelection | Checkbox Seleção e configuração de registros desativados. | boolean | TableRowSelection<Row> | false |
selectedRowKeys | bind:selectedRowKeys; Status removido de rowSelection. | TableKey[] | Estado local |
defaultSelectedRowKeys | Seleção inicial. | readonly TableKey[] | [] |
onSelectionChange | Retorna as chaves e as entradas selecionadas de dataSource, incluindo descendentes em ramificações dobradas. | (keys, rows, {type: single | all}) => void | — |
onChange | Status de filtros, classificação e páginas em um único objeto TableChange. | (change: TableChange<Row>) => void | — |
expandable | Configurações para expansão de entradas filho e strings de detalhes. | TableExpandable<Row> | — |
loading | Download e opções Spin incluindo atraso e assinatura. | boolean | SpinProps | false |
locale | Assinaturas locais de filtros, ações e estado vazio. | TableLocaleOverrides | de ConfigProvider |
tableLayout | Algoritmo para calcular a largura da coluna de uma tabela normal. | 'auto' | 'fixed' | Automático |
components | próprias linhas e células ou um corpo de rolagem separado. | TableComponents<Row> | — |
classNames | Classes de elementos de tabela nomeados. | TableSemantic<Row, TableClassNameSlots> | — |
styles | Strings CSS Para elementos de tabela nomeados. | TableSemantic<Row> | — |
rootClassName | Classe adicional do painel de raiz e filtro. | string | — |
disabled | Desative a seleção, classificação, filtragem e paginação. | boolean | ConfigProvider.componentDisabled |
bordered | Limites de células. | boolean | false |
size | Tamanho da linha; medium Adiciona um sufixo -medium ao prefixo da tabela permitida. | small | medium | large | ConfigProvider.componentSize |
caption | Assinatura nativa da mesa, separada do visual title/footer. | RenderEmptyContent | — |
title | Painel acima da tabela. Obtém entradas classificadas e filtradas da página atual; No servidor — transmitido dataSource. | Snippet<[readonly Row[]]> | — |
footer | Painel sob a tabela com as mesmas entradas da página atual; Não summary e não TFOOT. | Snippet<[readonly Row[]]> | — |
showHeader | Mostrar Thead; Ocultar salva caption, strings e status de classificação/filtro. | boolean | true |
rowClassName | classe de string. Índice - posição entre as linhas visíveis da página, recuo - o nível de aninhamento. | string | (record, index, indent) => string | — |
onRow | Atributos e manipuladores de string. O índice refere-se à página aberta. | (record, index) => TableRowProps | void | — |
onHeaderRow | Atributos e manipuladores da string de cabeçalho. O índice define o nível. | (columns, index) => TableRowProps | void | — |
rowHoverable | Iluminação flutuante; Não desativa a seleção, o foco e a ação da string. | boolean | true |
empty | Conteúdo na ausência de entradas e loading=false. | Snippet | RenderEmpty / Empty |
scroll | Role as dimensões e a posição redefinida após a ação. | TableScrollOptions | ConfigProvider.table.scroll |
virtual | Limita o número de linhas no DOM em uma determinada altura de scroll.y. | boolean | false |
onScroll | Área de evento de rolagem. No modo virtual, refere-se ao eixo vertical. | (event: Event & { currentTarget: HTMLDivElement }) => void | — |
nativeElement | Raiz Node DOM via bind:nativeElement. | HTMLDivElement | — |
sticky | Corrige o cabeçalho e a barra de rolagem horizontal. | boolean | TableSticky | false |
summary | Total de linhas da página atual com a configuração do pino superior ou inferior. | Snippet<[data: readonly Row[]]> | TableSummaryConfig<Row> | — |
id | é passado para o contêiner interno da tabela junto com os atributos data-*. | string | — |
role | Aplica-se ao elemento da tabela junto com os atributos aria-*. | HTMLTableAttributes["role"] | — |
aria-label | Nome da tabela disponível sem caption. | string | caption / locale |
class | Classe wrapper externa. | string | — |
style | CSS wrapper externo. | string | — |
TableColumnInput
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
children | Colunas sob o título geral do grupo. | readonly TableColumnInput<Row>[] | — |
responsive | Pontos de fratura Grid para os quais a coluna de nível superior é visível. | readonly GridBreakpoint[] | — |
colSpan | Largura da célula do cabeçalho nas colunas. Zero esconde a célula. | number | — |
rowSpan | Altura da célula do cabeçalho em linhas. Zero esconde a célula. | number | — |
onCell | Atributos e dimensões da célula. O índice refere-se à página aberta. | (record, index) => TableCellProps | void | — |
onHeaderCell | Atributos de cabeçalho. Pode substituir colSpan e rowSpan colunas. | (column) => TableCellProps | void | — |
hidden | Oculte a coluna do DOM sem remover sua classificação e filtros. fixed Deslocamentos Somente as colunas visíveis são levadas em consideração. | boolean | false |
className | Classe de cabeçalho e células de coluna. | string | — |
rowScope | Torna as células de dados reais th com o escopo especificado. | row | rowgroup | — |
key | sem key Use o caminho dataIndex ou posição. Em Filtros e classificação, a chave é String. | string | number | dataIndex / position |
title | Texto, número, matriz ou trecho com filtros e classificação atuais. | TableColumnTitle<Row> | — |
dataIndex | Chave de registro ou caminho para o valor aninhado. | TableDataIndex<Row> | — |
render | Obtém uma entrada, índice entre vizinhos e o valor original. | Snippet<[record: Row, index: number, value?: unknown]> | Valor dataIndex |
shouldCellUpdate | Decide se aceita uma nova entrada para o conteúdo da célula. | (record: Row, previousRecord: Row) => boolean | — |
sorter | Comparador, objeto de prioridade multiple ou critério do servidor. | boolean | TableSortCompare<Row> | TableColumnSorter<Row> | — |
sortOrder | Direção especificada pelo aplicativo. null Limpa o critério. | TableSortOrder | null | — |
defaultSortOrder | Direção de classificação inicial da coluna. | TableSortOrder | null | — |
sortDirections | Sua própria troca de ordem direcional na coluna. | readonly (TableSortOrder | null)[] | Da tabela |
sortIcon | Seu próprio ícone de classificação com a direção atual. | Snippet<[{ sortOrder: TableSortOrder | null }]> | — |
showSorterTooltip | Classificando as configurações de prompt para uma coluna. | boolean | TableSorterTooltipProps | Da tabela |
filters | Opções de filtro com elementos filho opcionais. | readonly TableFilterOption[] | — |
filterMode | menu ou árvore de opções. | 'menu' | 'tree' | menu |
filterSearch | Pesquisa por assinatura ou condição de aplicativo. | TableFilterSearch | false |
filtered | Destaca o filtro ativo, independentemente dos valores. | boolean | false |
filteredValue | Valores de coluna aplicadas sob controle de aplicativo. | readonly TableFilterValue[] | null | — |
defaultFilteredValue | Iniciar os valores do filtro da coluna. | readonly TableFilterValue[] | null | — |
filterResetToDefaultFilteredValue | Reset Restaure os valores iniciais no rascunho. | boolean | false |
filterDropdown | Painel de filtro próprio com rascunho e operações nele. | RenderEmptyContent | Snippet<[info: TableFilterDropdownProps]> | — |
filterDropdownProps | onOpenChange(open) Relata a abertura e o fechamento do painel. A escolha do item altera o filtro de rascunho e deixa o painel aberto. | TableFilterDropdownOptions | — |
filterOnClose | Aplica o rascunho do painel interno quando o usuário fecha. | boolean | false |
filterIcon | Seu ícone de filtro com sinal de atividade. | RenderEmptyContent | Snippet<[filtered: boolean]> | — |
onFilter | Verificação local de um registro. | (value, record) => boolean | — |
filterMultiple | Permitir vários valores de filtro. | boolean | true |
align | Alinhando o texto das células. | TableAlign | CSS |
width | largura col; Números em px. | number | string | Automático |
minWidth | Largura mínima do pixel em auto e na janela virtual. | number | — |
ellipsis | Cortar o texto. showTitle Controla o prompt da célula nativa. | boolean | { showTitle?: boolean } | false |
fixed | sticky coluna; true significa start. Se as colunas fixas não se encaixam, a fixação é desligada. | boolean | start | end | false |
TableRowSelection
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
type | Selecionando várias linhas ou uma linha. | 'checkbox' | 'radio' | checkbox |
selectedRowKeys | Chaves gerenciadas. Tenha precedência sobre a propriedade table com o mesmo nome. | readonly TableKey[] | Estado local |
defaultSelectedRowKeys | Seleção inicial. | readonly TableKey[] | [] |
onChange | Novas chaves, registros disponíveis e método de seleção. | (keys, rows, { type: TableRowSelectMethod }) => void | — |
onSelect | Ação com uma linha. Chamado antes onChange. | (record, checked, rows, event) => void | — |
preserveSelectedRowKeys | Salva as chaves e lembra as entradas selecionadas ao alterar dataSource. | boolean | false |
selections | Menu Checkbox com comandos regulares ou personalizados. | boolean | readonly (TableSelectionItem | TableSelectionPreset)[] | false |
hideSelectAll | Oculta a caixa de seleção e o menu de seleção no título. | boolean | false |
getTitleCheckboxProps | Atributos e manipuladores de caixa de seleção no cabeçalho. | () => TableSelectionControlProps | — |
columnTitle | Conteúdo do título da seleção. O trecho recebe a bandeira original. | RenderEmptyContent | Snippet<[checkbox: Snippet | undefined]> | — |
renderCell | O conteúdo da célula de seleção com acesso ao campo padrão via origem. | Snippet<[checked, record, index, origin]> | — |
onCell | Tamanho da célula de seleção e dimensões da célula. | (record, index) => TableCellProps | void | — |
checkStrictly | Para false Pais e descendentes estão vinculados. | boolean | true |
fixed | Proteja a coluna de seleção na borda lógica. | TableFixed | false |
columnWidth | Largura da coluna de seleção. | number | string | selectionColumnWidth |
align | Alinhando o conteúdo da coluna de seleção. | TableAlign | — |
getCheckboxProps | Atributos específicos de seleção de strings, incluindo disabled e aria-label. | (record) => TableSelectionControlProps | — |
TableExpandable
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
expandedRowRender | Conteúdo de uma string de detalhes separada, incluindo tabela aninhada. | Snippet<[record: Row, index: number, indent: number, expanded: boolean]> | — |
forceRender | Salva o conteúdo dos detalhes quando a linha é recolhida. | boolean | false |
expandedRowClassName | Detalhes e entradas aninhadas. | string | (record, index, indent) => string | — |
expandIcon | Comutador próprio com status de abertura e botão de origem padrão. | Snippet<[info: TableExpandIconInfo<Row>, origin: Snippet]> | — |
expandedRowKeys | Chaves gerenciadas dentro expandable. O proprietário aceita uma nova matriz em onExpandedRowsChange. | readonly TableKey[] | Estado local |
defaultExpandedRowKeys | Registros divulgados iniciais. lê uma vez; A mudança subsequente não redefine o estado. | readonly TableKey[] | [] |
defaultExpandAllRows | Revela as ramificações da página inicial se defaultExpandedRowKeys não for especificado. | boolean | false |
childrenColumnName | Nome do campo com registros filhos. | string | children |
indentSize | Preenchimento de nível de nidificação em pixels. | number | 15 |
expandRowByClick | Alterna a divulgação ao clicar na linha. | boolean | false |
showExpandColumn | Mostra a coluna Detalhes ou o botão na árvore. | boolean | true |
onExpand | Solicitação de divulgação de uma linha; Chamado antes onExpandedRowsChange. | (expanded, record) => void | — |
onExpandedRowsChange | Novo conjunto completo de chaves, incluindo outras páginas. Para o estado gerenciado, atualize expandable.expandedRowKeys. | (keys: TableKey[]) => void | — |
rowExpandable | Quais entradas estão disponíveis para obter detalhes. | (record) => boolean | true |
columnTitle | Coluna do Serviço de Título. | RenderEmptyContent | Cabeçalho vazio |
columnWidth | Abrindo a largura da coluna. | number | string | 48px |
fixed | Proteja a coluna de abertura na borda lógica. | TableFixed | false |
TableRef
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
scrollTo | Mover para a posição ou linha da página atual por tecla ou índice. | (config: TableScrollConfig) => void | — |
TableScrollOptions
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
x | Largura da tabela. true Seleciona-o de acordo com o conteúdo. | number | string | true | — |
y | Altura da área de rolagem. Para virtual especifique o número de pixels. | number | string | — |
scrollToFirstRowOnChange | Ir para Iniciar após a classificação do usuário, filtrando ou alterando a página. | boolean | virtual |
TablePaginationConfig
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
placement | Alinhar acima e abaixo da tabela. Uma lista vazia oculta a navegação. | readonly TablePaginationPlacement[] | bottomEnd |
TableSticky
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
offsetHeader | Topo preenchimento de cabeçalho em pixels. | number | 0 |
offsetSummary | Reduza a margem total em pixels. | number | 0 |
offsetScroll | Menor recuo de uma barra de rolagem adicional em pixels. | number | 0 |
getContainer | Retorna a área de rolagem. Por padrão, a janela da tabela é usada. | () => HTMLElement | Window | null | undefined | — |
TableChange
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
action | Motivo da mudança. | sort | paginate | filter | — |
pagination | página e tamanho reais. | {current, pageSize, total} | — |
sorter | Primeiro critério ativo. | TableSorter | null | — |
sorters | Todos os critérios ativos ao classificar por várias colunas. | TableSorter[] | — |
filters | valores para as teclas de coluna quando a mesa possui filtros. | TableFilters | undefined | — |
currentDataSource | Raízes com registros filhos. No modo cliente - após o processamento antes da paginação. | Row[] | — |
TableSorter
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
columnKey | key Coluna classificável. | string | Obrigatório |
order | Direção; null Total sorter significa nenhuma classificação. | ascend | descend | Obrigatório |
TableFilterOption
| Propriedade | Descrição | Tipo | Valor padrão |
|---|---|---|---|
text | Assinatura da opção. | RenderEmptyContent | Obrigatório |
value | Valor em filters e onFilter. | string | number | boolean | Obrigatório |
children | Opções no grupo de filtros. | readonly TableFilterOption[] | — |
Handler onChange Obtém Objeto TableChange. Snippet render Obtém uma entrada, um índice e um valor original. Grupos de colunas são definidos por children em columns.
Semantic DOM
Para itens nomeados, use classNames e styles. As configurações do provedor e da tabela são combinadas por item.
As classes abaixo são mostradas para o padrão ant-table. prefixCls Substitui essa parte dos nomes; Marcador ant-table-css-var é salvo. Checkbox, Button e Pagination de forma independente, use o provedor geral de prefixos; A paginação também recebe uma classe Owner de tabela com -pagination. dropdownPrefixCls Somente altera o nome da lista dentro do filtro, com o sufixo -menu.
| Elemento | Atribuir |
|---|---|
.ant-table-wrapper | raiz class/style e direção RTL. |
.ant-table-content | Focalável role=region com rolagem interna. |
table / caption | estrutura nativa da tabela e nome disponível. |
.ant-table-thead | TH CO cabeçalhos scope=col ou COLGROUP e status aria-sort. |
.ant-table-column-sorters | Botão de classificação disponível no teclado. |
.ant-table-tbody | Linhas de dados. |
.ant-table-selection-column | Caixa de seleção e comandos no cabeçalho, caixa de seleção ou rádio em linhas. |
tfoot | Strings Table.Summary. |
.ant-table-sticky-scroll | Barra de rolagem horizontal adicional. |
.ant-table-row-expand-icon | Botão de lançamento com aria-expanded/aria-controls. |
.ant-table-expanded-row | Detalhes String. |
.ant-table-placeholder | Conteúdo empty Na ausência de entradas. |
.ant-table-title / .ant-table-footer | Painéis visuais com a página atual. |
th[scope=row] / th[scope=rowgroup] | Cabeçalhos de string definidos column.rowScope. |
.ant-table-pagination | Paginação de navegação separada. |
| Elemento | Atribuir |
|---|---|
root | Recipiente externo. |
section | Recipiente ao redor da área de rolagem. |
content | Área de rolagem de uma tabela normal sem um cabeçalho fixo. |
title / footer | Painel acima e abaixo da tabela. |
header.wrapper / header.row / header.cell | Cap shell, suas strings e células. |
body.wrapper / body.row / body.cell | Corpo, string de dados e célula. |
pagination.root / pagination.item | Recipiente e pontos de paginação. |
Tokens de design
Defina o design da mesa via theme.components.Table. Redimensionamento de tokens, plano de fundo, bordas, filtros e barra de rolagem fixada.
| Token | Atribuir |
|---|---|
headerBg | fundo de chapéu. |
headerColor | Texto. |
headerSortActiveBg | Fundo de cabeçalho classificável. |
headerSortHoverBg | Passar o cabeçalho classificável. |
bodySortBg | Fundo de coluna ordenada. |
rowHoverBg | Passe o mouse. |
rowSelectedBg | linha selecionada. |
rowSelectedHoverBg | Passe o mouse sobre a string selecionada. |
rowExpandedBg | Fundo de detalhes. |
cellPaddingBlock | Preenchimento vertical large. |
cellPaddingInline | Preenchimento horizontal large. |
cellPaddingBlockMD | Preenchimento vertical medium. |
cellPaddingInlineMD | Preenchimento horizontal medium. |
cellPaddingBlockSM | Preenchimento vertical small. |
cellPaddingInlineSM | Preenchimento horizontal small. |
borderColor | Cor da borda. |
headerBorderRadius | Raio do chapéu. |
footerBg | Fundo do painel footer. |
footerColor | Texto do painel footer. |
cellFontSize | Fonte large. |
cellFontSizeMD | Fonte medium. |
cellFontSizeSM | Fonte small. |
headerSplitColor | divisor de tampas. |
fixedHeaderSortActiveBg | Classificando o cabeçalho fixado. |
headerFilterHoverBg | Filtro de foco. |
filterDropdownMenuBg | Filtro de fundo do menu. |
filterDropdownBg | Fundo do painel do filtro. |
expandIconBg | Fundo de divulgação. |
selectionColumnWidth | Largura da coluna da caixa de seleção. |
stickyScrollBarBg | O plano de fundo da barra de rolagem fixada. |
stickyScrollBarBorderRadius | O raio da barra de rolagem fixada. |
expandIconMarginTop | Top recuo de abertura. |
expandIconHalfInner | Geometria do ícone de lançamento. |
expandIconSize | Tamanho da divulgação. |
expandIconScale | Escala de divulgação. |
headerIconColor | Ícones de chapéus. |
headerIconHoverColor | Ícones do chapéu. |
| Token | Valor |
|---|---|
colorBgContainer | #ffffff |
colorText | rgba(0,0,0,0.88) |
colorTextHeading | rgba(0,0,0,0.88) |
colorPrimary | #2f54eb |
colorBorderSecondary | #f0f0f0 |
fontSize | 14 |
lineHeight | 1.5714285714285714 |
paddingSM | 12 |
FAQ
Por que rowKey é realmente necessário?
sem explícito rowKey Leia record.key. Escolha do link, divulgação e DOM exclusivos do link de chaves; O índice de strings visíveis não se encaixa.
Como o servidor mode é organizado?
App processa TableChange e transfere a página finalizada, total e loading. A tabela não carrega dados.
Por que não é possível reagir-exemplo onChange ser literalmente copiado?
Svelte Obtém um objeto TableChange. Os estados de classificação, filtro, página e seleção estão na mesa; render As colunas recebem registro/index, a abertura é controlada via expandable.
O que todas as linhas escolhem?
A caixa de seleção Cabeçalho marca as linhas disponíveis da página atual e armazena as chaves de outras páginas. O comando Select All no menu cobre todo o conjunto de dados após a filtragem.
Por que o filtro retorna à primeira página?
Após o filtro, a página anterior pode estar ausente. O estado gerenciado permite que o aplicativo corresponda à página e ao total total.
Como adicionar colunas de edição e ocultação?
Use render Snippet e atualize dataSource Para edição, column.hidden para ocultar. Exemplos armazenam chaves de string estáveis.
Como o tema afeta o tamanho da paginação?
Tabela de tamanhos medium O padrão usa paginação small. Em Exemplo de prefixo a altura do ponto é 24 px em um tema normal e 21 px em um compacto. Alterar o prefixo no mesmo tema mantém a altura dos itens e da tabela.