242 lines
11 KiB
Markdown
242 lines
11 KiB
Markdown
---
|
|
name: tanstack-table-and-charts
|
|
description: >-
|
|
Comprehensive guide and design patterns for building high-performance,
|
|
accessible data tables and dynamic visualizations using @tanstack/react-table
|
|
and @tanstack/charts in React. Integrated with glassmorphism, SENA institutional
|
|
colors, responsive mobile-first scrolling, and dark mode.
|
|
---
|
|
|
|
# TanStack Table and TanStack Charts Skill
|
|
|
|
This skill guides the implementation of headless, high-density data tables (`@tanstack/react-table`) and declarative data visualizations (`@tanstack/charts`) in React, seamlessly styled with Tailwind CSS, glassmorphism, and the institutional CPIC/SENA design system.
|
|
|
|
---
|
|
|
|
## 1. Package Installation & Dependencies
|
|
|
|
```bash
|
|
# TanStack Table (v8)
|
|
npm install @tanstack/react-table
|
|
|
|
# TanStack Charts (Latest)
|
|
npm install @tanstack/charts
|
|
```
|
|
|
|
---
|
|
|
|
## 2. TanStack Table (`@tanstack/react-table`)
|
|
|
|
TanStack Table is a headless library providing 100% control over markup and styling while handling complex state (sorting, filtering, pagination, selection, grouping).
|
|
|
|
### A. Core Architecture Pattern
|
|
```jsx
|
|
import React, { useMemo, useState } from 'react';
|
|
import {
|
|
useReactTable,
|
|
getCoreRowModel,
|
|
getSortedRowModel,
|
|
getFilteredRowModel,
|
|
getPaginationRowModel,
|
|
flexRender,
|
|
createColumnHelper,
|
|
} from '@tanstack/react-table';
|
|
|
|
const columnHelper = createColumnHelper();
|
|
|
|
export const DataTable = ({ data, columns }) => {
|
|
const [sorting, setSorting] = useState([]);
|
|
const [globalFilter, setGlobalFilter] = useState('');
|
|
|
|
const table = useReactTable({
|
|
data,
|
|
columns,
|
|
state: {
|
|
sorting,
|
|
globalFilter,
|
|
},
|
|
onSortingChange: setSorting,
|
|
onGlobalFilterChange: setGlobalFilter,
|
|
getCoreRowModel: getCoreRowModel(),
|
|
getSortedRowModel: getSortedRowModel(),
|
|
getFilteredRowModel: getFilteredRowModel(),
|
|
getPaginationRowModel: getPaginationRowModel(),
|
|
initialState: {
|
|
pagination: { pageSize: 10 },
|
|
},
|
|
});
|
|
|
|
return (
|
|
<div className="flex flex-col gap-3 w-full">
|
|
{/* 1. Barra de Búsqueda y Filtro */}
|
|
<div className="flex items-center justify-between gap-3">
|
|
<div className="relative flex-1 max-w-sm">
|
|
<i className="fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-white/40 text-xs" />
|
|
<input
|
|
type="text"
|
|
value={globalFilter ?? ''}
|
|
onChange={e => setGlobalFilter(e.target.value)}
|
|
placeholder="Buscar en la tabla..."
|
|
className="w-full pl-8 pr-3 py-1.5 text-xs rounded-xl bg-white/70 dark:bg-white/5 border border-black/10 dark:border-white/10 text-gray-900 dark:text-white placeholder:text-gray-400 dark:placeholder:text-white/30 focus:outline-none focus:border-[#39A900] dark:focus:border-lime transition-all"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{/* 2. Contenedor Glassmorphism con Scrollbar Responsive */}
|
|
<div className="overflow-x-auto custom-scrollbar w-full rounded-2xl border border-black/8 dark:border-white/10 bg-white/75 dark:bg-[rgba(10,22,10,0.8)] backdrop-blur-xl shadow-xs">
|
|
<table className="w-full text-left text-xs border-collapse min-w-[600px]">
|
|
{/* Encabezado Institucional SENA */}
|
|
<thead className="bg-[#39A900] dark:bg-[rgba(57,169,0,0.85)] text-white font-semibold text-[11px] sticky top-0 z-10 select-none">
|
|
{table.getHeaderGroups().map(headerGroup => (
|
|
<tr key={headerGroup.id}>
|
|
{headerGroup.headers.map(header => {
|
|
const canSort = header.column.getCanSort();
|
|
const isSorted = header.column.getIsSorted();
|
|
return (
|
|
<th
|
|
key={header.id}
|
|
onClick={header.column.getToggleSortingHandler()}
|
|
className={`py-2.5 px-3.5 whitespace-nowrap ${canSort ? 'cursor-pointer hover:bg-black/10 transition-colors' : ''}`}
|
|
>
|
|
<div className="flex items-center gap-1.5">
|
|
{flexRender(header.column.columnDef.header, header.getContext())}
|
|
{canSort && (
|
|
<span className="opacity-75 text-[10px]">
|
|
{isSorted === 'asc' ? (
|
|
<i className="fa-solid fa-arrow-up-long text-lime" />
|
|
) : isSorted === 'desc' ? (
|
|
<i className="fa-solid fa-arrow-down-long text-lime" />
|
|
) : (
|
|
<i className="fa-solid fa-sort opacity-40 hover:opacity-100" />
|
|
)}
|
|
</span>
|
|
)}
|
|
</div>
|
|
</th>
|
|
);
|
|
})}
|
|
</tr>
|
|
))}
|
|
</thead>
|
|
|
|
{/* Cuerpo con Zebra Striping y Hover Glass */}
|
|
<tbody>
|
|
{table.getRowModel().rows.length > 0 ? (
|
|
table.getRowModel().rows.map(row => (
|
|
<tr
|
|
key={row.id}
|
|
className="border-b border-black/5 dark:border-white/5 even:bg-black/[0.015] dark:even:bg-white/[0.015] hover:bg-[#39A900]/8 dark:hover:bg-lime/8 transition-colors"
|
|
>
|
|
{row.getVisibleCells().map(cell => (
|
|
<td key={cell.id} className="py-2.5 px-3.5 text-gray-800 dark:text-gray-200">
|
|
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
|
</td>
|
|
))}
|
|
</tr>
|
|
))
|
|
) : (
|
|
<tr>
|
|
<td colSpan={columns.length} className="py-10 text-center text-gray-400 dark:text-white/40">
|
|
<i className="fa-regular fa-folder-open text-2xl mb-2 opacity-50 block" />
|
|
No se encontraron resultados
|
|
</td>
|
|
</tr>
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
|
|
{/* 3. Paginación Glassmorphic */}
|
|
<div className="flex items-center justify-between text-xs text-gray-600 dark:text-white/60 px-1 py-1">
|
|
<span>
|
|
Página {table.getState().pagination.pageIndex + 1} de {table.getPageCount()} ({table.getFilteredRowModel().rows.length} registros)
|
|
</span>
|
|
<div className="flex items-center gap-1">
|
|
<button
|
|
onClick={() => table.previousPage()}
|
|
disabled={!table.getCanPreviousPage()}
|
|
className="px-2.5 py-1 rounded-lg border border-black/10 dark:border-white/10 bg-black/5 dark:bg-white/5 hover:bg-black/10 dark:hover:bg-white/10 disabled:opacity-40 disabled:cursor-not-allowed transition-all"
|
|
>
|
|
<i className="fa-solid fa-chevron-left text-[10px] mr-1" /> Ant
|
|
</button>
|
|
<button
|
|
onClick={() => table.nextPage()}
|
|
disabled={!table.getCanNextPage()}
|
|
className="px-2.5 py-1 rounded-lg border border-black/10 dark:border-white/10 bg-black/5 dark:bg-white/5 hover:bg-black/10 dark:hover:bg-white/10 disabled:opacity-40 disabled:cursor-not-allowed transition-all"
|
|
>
|
|
Sig <i className="fa-solid fa-chevron-right text-[10px] ml-1" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
```
|
|
|
|
---
|
|
|
|
## 3. TanStack Charts (`@tanstack/charts`)
|
|
|
|
`@tanstack/charts` es la biblioteca de gráficos moderna y modular de TanStack. Emplea una gramática declarativa de visualización (escalas, series, ejes y tooltips) optimizada para renderizado rápido.
|
|
|
|
### A. Estructura y Componente con React Adapter
|
|
```jsx
|
|
import React from 'react';
|
|
import { Chart } from '@tanstack/charts/react';
|
|
import { defineChart, lineY, barY } from '@tanstack/charts';
|
|
|
|
export const PerformanceMetricsChart = ({ data }) => {
|
|
// data: [{ timestamp: '10:00', latency: 120, tokens: 450 }]
|
|
return (
|
|
<div className="relative rounded-2xl p-4 bg-white/75 dark:bg-[rgba(10,22,10,0.8)] backdrop-blur-xl border border-black/8 dark:border-white/10 shadow-[0_4px_20px_rgba(0,0,0,0.05)]">
|
|
{/* Título de la tarjeta */}
|
|
<div className="flex items-center justify-between mb-3">
|
|
<div className="flex items-center gap-2">
|
|
<span className="w-6 h-6 rounded-lg bg-[#39A900]/15 dark:bg-lime/20 text-[#39A900] dark:text-lime flex items-center justify-center text-xs">
|
|
<i className="fa-solid fa-chart-line" />
|
|
</span>
|
|
<h4 className="text-xs font-bold text-gray-900 dark:text-white uppercase tracking-wider">
|
|
Latencia de Respuestas (ms)
|
|
</h4>
|
|
</div>
|
|
<span className="text-[10px] font-mono text-gray-500 dark:text-white/40">
|
|
En tiempo real
|
|
</span>
|
|
</div>
|
|
|
|
{/* Contenedor del Gráfico */}
|
|
<div className="h-64 w-full">
|
|
{/* Usar Chart de @tanstack/charts/react con la paleta de colores institucional */}
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
```
|
|
|
|
### B. Paleta de Colores y Gráficos Institucionales (SENA)
|
|
Para gráficos consistentes con el diseño del sistema:
|
|
- **Línea Principal / Métrica Primaria**: `#39A900` (Modo claro) / `#a3e635` (Modo oscuro / `lime-400`).
|
|
- **Métrica Secundaria / Comparativa**: `#0284c7` (Cyan 600) / `#38bdf8` (Cyan 400).
|
|
- **Métrica de Alerta / Errores**: `#ef4444` (Red 500).
|
|
- **Gradiente de Área**: Gradiente vertical translúcido desde `rgba(57, 169, 0, 0.35)` hasta `rgba(57, 169, 0, 0.0)`.
|
|
- **Líneas de Guía (Grid)**: `rgba(0, 0, 0, 0.06)` (Claro) / `rgba(255, 255, 255, 0.06)` (Oscuro).
|
|
- **Tooltips**: Contenedores flotantes con `backdrop-blur-md`, fondo `rgba(10, 22, 10, 0.9)` y borde `border-white/10`.
|
|
|
|
---
|
|
|
|
## 4. Cuándo Usar Cada Herramienta
|
|
|
|
| Caso de Uso | Herramienta Recomendada | Beneficios |
|
|
| :--- | :--- | :--- |
|
|
| **Tablas CRUD & Administración** | `@tanstack/react-table` | Control total de columnas, ordenamiento, filtrado global y renderizado de celdas con botones/acciones. |
|
|
| **Horarios & Matriz CRONODE** | `CronodeTableView` + `@tanstack/react-table` | Visualización estructurada con exportación PDF/Excel y alternancia a tarjetas/calendario. |
|
|
| **Monitoreo de Latencia / Tokens** | `@tanstack/charts` | Gráficos de series de tiempo reactivos, ligeros y estilizables con el tema del sistema. |
|
|
| **Distribución de Roles & Categorías** | `@tanstack/charts` (Bar / Donut) | Claridad visual en el Dashboard Administrativo con paleta SENA. |
|
|
|
|
---
|
|
|
|
## 5. Reglas de Integración con el Sistema CPIC
|
|
1. **No mezclar CSS ad-hoc**: Siempre usar las clases de diseño institucional (`text-[#39A900]`, `dark:text-lime`, `border-black/8`, `dark:border-white/10`).
|
|
2. **Scroll Horizontal Obligatorio**: Nunca permitir que tablas de más de 4 columnas fuercen overflow en la página; siempre encerrarlas en un contenedor `overflow-x-auto custom-scrollbar`.
|
|
3. **Optimización con Memoization**: Las definiciones de columnas `columns` y la data deben envolverse en `useMemo` para evitar re-computación de la tabla en cada render.
|