EditableTable
Una tabla en la que la gente trabaja: cada celda que puede cambiar se edita en su lugar, el guardado se ve en la celda, y un valor rechazado se queda con su razón. Las filas se agregan arriba, las filas marcadas cambian juntas, y la tabla se exporta a CSV.
import { DataTable } from '@sypnia/ui/react'
En un computador
Haz doble clic en un precio y escribe un número negativo: se rechaza. Marca filas para archivarlas (con Deshacer) o borrarlas. Agrega una fila, oculta columnas, exporta.
products
La tabla products de northwind-shop. Haz doble clic en una celda para cambiarla.
Código
import { useMemo, useState } from 'react';
import {
Badge, Button, ConfirmDialog, DataTable, EmptyState, Page, PageHeader, SkeletonOf, SkeletonWords, Toaster, toast, useSypnia, type DataColumn, type RowKey,
} from '@sypnia/ui/react';
// A table people work in: every cell they may change is edited in place (double-click, or Enter), saving shows in the
// cell, and a refused value stays with its reason. Rows are added at the top, ticked rows are changed or deleted
// together, and the whole table goes to CSV. On phones each row is a card.
const en = {
title: 'products', lead: 'The table products of northwind-shop. Double-click a cell to change it.', add: 'Add row', import: 'Import CSV',
sku: 'SKU', name: 'Name', price: 'Price', stock: 'Stock', status: 'Status', statuses: ['Active', 'Draft', 'Archived'],
newName: 'New product', added: 'Row added at the top. Give it a name and a price.', negative: 'A price cannot be below zero.', noStock: 'Stock must be a whole number, 0 or more.',
archive: 'Archive', del: 'Delete', delQ: (n: number) => (n === 1 ? 'Delete 1 row?' : `Delete ${n} rows?`), delBody: 'They leave the table products now. Orders that point to them keep their copy of the name and price.',
deleted: (n: number) => (n === 1 ? '1 row deleted' : `${n} rows deleted`), archived: (n: number) => (n === 1 ? '1 row archived' : `${n} rows archived`), undo: 'Undo',
emptyTitle: 'products has no rows yet', emptyBody: 'Add the first one here, import a CSV, or write to it from your app: every row appears here at once.',
failed: 'The rows of products could not be loaded. The table and its data are safe.',
};
const es: typeof en = {
title: 'products', lead: 'La tabla products de northwind-shop. Haz doble clic en una celda para cambiarla.', add: 'Agregar fila', import: 'Importar CSV',
sku: 'SKU', name: 'Nombre', price: 'Precio', stock: 'Existencias', status: 'Estado', statuses: ['Activo', 'Borrador', 'Archivado'],
newName: 'Producto nuevo', added: 'Fila agregada arriba. Ponle un nombre y un precio.', negative: 'Un precio no puede ser menor que cero.', noStock: 'Las existencias deben ser un número entero, 0 o más.',
archive: 'Archivar', del: 'Borrar', delQ: (n: number) => (n === 1 ? '¿Borrar 1 fila?' : `¿Borrar ${n} filas?`), delBody: 'Salen ya de la tabla products. Los pedidos que las usan conservan su copia del nombre y el precio.',
deleted: (n: number) => (n === 1 ? '1 fila borrada' : `${n} filas borradas`), archived: (n: number) => (n === 1 ? '1 fila archivada' : `${n} filas archivadas`), undo: 'Deshacer',
emptyTitle: 'products aún no tiene filas', emptyBody: 'Agrega la primera aquí, importa un CSV, o escribe desde tu app: cada fila aparece aquí al instante.',
failed: 'No se pudieron cargar las filas de products. La tabla y sus datos están a salvo.',
};
interface Product { sku: string; name: string; price: number; stock: number; status: number }
const seed: Product[] = [
['NW-1001', 'Oak desk lamp', 48, 120, 0], ['NW-1002', 'Linen cushion', 22, 340, 0], ['NW-1003', 'Stoneware mug, set of 4', 36, 0, 0],
['NW-1004', 'Walnut side table', 210, 14, 0], ['NW-1005', 'Wool throw', 89, 57, 1], ['NW-1006', 'Brass wall hook', 12, 800, 0],
['NW-1007', 'Rattan basket', 31, 96, 0], ['NW-1008', 'Ceramic vase', 44, 23, 2], ['NW-1009', 'Cotton apron', 19, 210, 0],
['NW-1010', 'Pine bookshelf', 160, 8, 1], ['NW-1011', 'Glass carafe', 27, 150, 0], ['NW-1012', 'Jute rug, 2×3 m', 240, 5, 0],
].map(([sku, name, price, stock, status]) => ({ sku, name, price, stock, status }) as Product);
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
export default function EditableTable({ state = 'ready' }: { state?: 'ready' | 'loading' | 'empty' | 'error' }) {
const { locale, format } = useSypnia();
const c = locale.startsWith('es') ? es : en;
const [rows, setRows] = useState<Product[]>(state === 'empty' ? [] : seed);
const [selected, setSelected] = useState<Set<RowKey>>(new Set());
const [confirm, setConfirm] = useState<string[] | null>(null);
const [failed, setFailed] = useState(state === 'error');
const [next, setNext] = useState(1013);
const tones = ['ok', 'neutral', 'warn'] as const;
// Loading: the real table, toolbar and columns; as many rows as the last visit, each value as long as a real one.
const columns: DataColumn<Product>[] = useMemo(() => [
{ id: 'sku', header: c.sku, icon: 'primary-key', machine: true, width: 120, value: (p) => p.sku, sortable: true, skeleton: (i) => <SkeletonWords>{seed[i % seed.length].sku}</SkeletonWords> },
{ id: 'name', header: c.name, width: 240, value: (p) => p.name, editable: true, sortable: true, filter: 'text', skeleton: (i) => <SkeletonWords>{seed[i % seed.length].name}</SkeletonWords> },
{ id: 'price', header: c.price, note: 'USD', numeric: true, width: 120, value: (p) => p.price, render: (p) => format.currency(p.price, 'USD'), editable: true, editor: 'number', sortable: true,
skeleton: (i) => <SkeletonWords>{format.currency(seed[i % seed.length].price, 'USD')}</SkeletonWords> },
{ id: 'stock', header: c.stock, numeric: true, width: 120, value: (p) => p.stock, editable: (p) => p.status !== 2, editor: 'number', sortable: true,
skeleton: (i) => <SkeletonWords>{seed[i % seed.length].stock}</SkeletonWords> },
{ id: 'status', header: c.status, width: 140, value: (p) => c.statuses[p.status], render: (p) => <Badge tone={tones[p.status]} dot>{c.statuses[p.status]}</Badge>,
editable: true, editor: 'select', options: c.statuses, filter: 'select', skeleton: (i) => <SkeletonOf><Badge dot>{c.statuses[seed[i % seed.length].status]}</Badge></SkeletonOf> },
], [c, format]); // eslint-disable-line react-hooks/exhaustive-deps
const save = async (p: Product, col: string, value: unknown) => {
await wait(500);
if (col === 'price' && Number(value) < 0) throw new Error(c.negative);
if (col === 'stock' && (!Number.isInteger(Number(value)) || Number(value) < 0)) throw new Error(c.noStock);
const v = col === 'status' ? c.statuses.indexOf(String(value)) : col === 'name' ? String(value) : Number(value);
setRows((all) => all.map((r) => (r.sku === p.sku ? { ...r, [col]: v } : r)));
};
const add = () => { setRows((all) => [{ sku: `NW-${next}`, name: c.newName, price: 0, stock: 0, status: 1 }, ...all]); setNext((n) => n + 1); toast(c.added); };
const toolbar = <><Button size="sm" icon="upload" href="#csv-import">{c.import}</Button><Button size="sm" variant="primary" icon="plus" onClick={add}>{c.add}</Button></>;
return (
<Page wide>
<PageHeader title={c.title} lead={c.lead} />
<DataTable label={c.title} columns={columns} rows={state === 'loading' ? undefined : rows} loading={state === 'loading'} loadingRows={seed} rowKey={(p) => p.sku}
onEdit={save} selectable selected={selected} onSelect={setSelected} columnPicker exportName="products" pageSize={25} toolbar={toolbar}
error={failed ? c.failed : undefined} onRetry={() => setFailed(false)}
empty={<EmptyState icon="table" compact title={c.emptyTitle} actions={toolbar}>{c.emptyBody}</EmptyState>}
bulkActions={(keys) => (
<>
<Button size="sm" icon="archive" onClick={() => {
const before = rows;
setRows((all) => all.map((r) => (keys.includes(r.sku) ? { ...r, status: 2 } : r))); setSelected(new Set());
toast(c.archived(keys.length), { action: { label: c.undo, onClick: () => setRows(before) } });
}}>{c.archive}</Button>
<Button size="sm" variant="danger" icon="trash" onClick={() => setConfirm(keys.map(String))}>{c.del}</Button>
</>
)} />
<ConfirmDialog open={confirm !== null} title={c.delQ(confirm?.length ?? 0)} action={c.del} onClose={() => setConfirm(null)}
onConfirm={() => { setRows((all) => all.filter((r) => !confirm!.includes(r.sku))); toast(c.deleted(confirm!.length), { tone: 'ok' }); setSelected(new Set()); setConfirm(null); }}>
<p>{c.delBody}</p>
</ConfirmDialog>
<Toaster />
</Page>
);
} En un celular
En un celular cada fila es una tarjeta; las acciones de las filas marcadas van de a dos.
Vacía
Una tabla aún sin filas: tres formas de llenarla.
products
La tabla products de northwind-shop. Haz doble clic en una celda para cambiarla.
products aún no tiene filas
Skeleton
La tabla real, con su barra y sus columnas, y tantas filas como en la última visita; cada valor es una barra tan larga como uno real, y en el celular cada tarjeta conserva sus cajas de edición.
products
La tabla products de northwind-shop. Haz doble clic en una celda para cambiarla.
Cuando las filas no cargan
La tabla conserva su marco; el mensaje dice que los datos están a salvo y ofrece «Intentar de nuevo».
products
La tabla products de northwind-shop. Haz doble clic en una celda para cambiarla.
No se pudieron cargar las filas de products. La tabla y sus datos están a salvo.
Cuándo usarlo
Úsalo cuando
- Las filas de una tabla en una consola de datos, una lista de productos o precios, cualquier lista que se edita a menudo.
- Rechazar un valor en la celda que lo tiene, con la razón, y conservar lo escrito.
No lo uses cuando
- Editar muchos campos de un registro: ábrelo en un Drawer o una FormPage.
- Borrar filas marcadas sin preguntar: di cuántas, y qué pasa con lo que las usa.
Para todos
- A las celdas se llega con las flechas; Enter edita, Escape cancela, Tab guarda y sigue.
- Una celda que se está guardando lo dice, y un valor rechazado se lee con su razón.
- En celulares cada fila es una tarjeta con los nombres de sus columnas.
Props
| DataTable | Tipo | Por defecto |
|---|---|---|
columnsobligatorio | DataColumn<Row>[] | |
labelobligatorioA name for screen readers. | string | |
rowKeyobligatorio | (row: Row) => RowKey | |
rowsobligatorioThe rows in memory: all of them (the table scrolls through thousands), or one page when `pagination` is set. | Row[] | undefined | |
bulkActionsButtons for the bar that appears while rows are selected. Receives the selected keys and the selected rows that are in memory. | ((keys: RowKey[], rows: Row[]) => ReactNode) | |
columnPickerAdds the «Columns» menu to the toolbar. | boolean | |
defaultHiddenIds of columns hidden at first. With `columnPicker` the person can change them. | string[] | |
defaultSort | DataSort | null | null |
emptyWhat to show when there are no rows at all: an EmptyState with the next step. | ReactNode | |
errorSomething failed: say what happened in plain words. | ReactNode | |
exportNameAdds «Export CSV» to the toolbar. This is the name of the file. It exports the selected rows, or all the rows shown. | string | |
filtersControlled filters, by column id. Leave it out and the table keeps its own. | DataFilters | |
heightThe tallest the grid gets before it scrolls: any CSS length. | string | min(32rem, 70dvh) |
layout`auto`: a grid on wide screens, cards on phones. Force one of them for a narrow panel or a preview. | "grid" | "cards" | "auto" | auto |
loadingData is on its way: rows are drawn as skeletons of the right shape. | boolean | |
loadingRowsHow many skeleton rows (cards on phones) to draw while loading: as many as will come. Default 8 rows, 3 cards. Or the rows of the last visit: as many, and on phones each card's values that can be edited wait in their edit box (an `editable` function is asked about each of them). | number | Row[] | |
onColumnWidthsCalled with every width, by column id, after the person resizes one. | ((widths: Record<string, number>) => void) | |
onEditSaves one value. Return a promise and the cell shows it is busy; reject it (or throw) and the cell keeps what was typed and shows the reason. | ((row: Row, columnId: string, value: unknown) => void | Promise<unknown>) | |
onFilter | ((filters: DataFilters) => void) | |
onRetryWith `error`: shows «Try again». | (() => void) | |
onSelect | ((selected: Set<RowKey>) => void) | |
onSort | ((sort: DataSort | null) => void) | |
pageSizeRows in memory are shown a page at a time (every table paginates). The person can change it. On phones a page holds at most 25 cards. | number | 100 |
pageSizesThe page sizes the person can choose from. | number[] | [50, 100, 250, 500] |
paginationServer pages: the table shows `rows` as one page and this bar under them. Without it the table pages the rows in memory itself (`pageSize`). | { page: number; pageSize: number; total: number; onPage: (page: number) => void; onPageSize?: ((size: number) => void); } | |
selectableAdds a checkbox to every row. | boolean | |
selectedControlled selection: the keys of the selected rows. | ReadonlySet<RowKey> | |
serverThe rows already arrive sorted and filtered (by a server): the table only reports what the person asked through `onSort` and `onFilter`. | boolean | |
sortControlled sort. Leave it out and the table keeps its own. | DataSort | null | |
toolbarExtra content at the start of the toolbar: a search field, a title. | ReactNode |