@isai_dev/data_table_lib 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jaziel Isaí
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,236 @@
1
- # Temporary Holding Version
1
+ # Data Table Lib
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Tablas React para mostrar, explorar, seleccionar y editar datos. Incluye `Table` y `TableEdit`, CSS independiente, tipos TypeScript y una demo.
4
+
5
+ Creada por [Jaziel Isaí](https://isai-dev.com).
6
+
7
+ Licencia [MIT](./LICENSE). Puedes usar, modificar y distribuir la librería conservando el aviso de copyright y la licencia.
8
+
9
+ ## Instalar y ejecutar
10
+
11
+ Requiere React y React DOM 18 o 19 en la aplicación. Para desarrollar o compilar este repositorio se recomienda Node.js 22.12+ (también 24 o 26 LTS); [Vite 8 admite Node 20.19+ o 22.12+](https://vite.dev/guide/). La librería está publicada en npm como [`@isai_dev/data_table_lib`](https://www.npmjs.com/package/@isai_dev/data_table_lib).
12
+
13
+ En tu proyecto:
14
+
15
+ ```bash
16
+ npm install @isai_dev/data_table_lib
17
+ ```
18
+
19
+ Después importa los componentes y el CSS:
20
+
21
+ ```jsx
22
+ import { Table, TableEdit } from '@isai_dev/data_table_lib';
23
+ import '@isai_dev/data_table_lib/style.css';
24
+ ```
25
+
26
+ Para desarrollar este repositorio:
27
+
28
+ ```bash
29
+ npm install
30
+ npm start # demo local
31
+ npm test # compila y ejecuta las pruebas
32
+ npm pack # crea el archivo instalable .tgz
33
+ ```
34
+
35
+ También puedes instalar el archivo generado con `npm install /ruta/al/archivo.tgz` si necesitas probar una compilación local.
36
+
37
+ ## Ejemplos ejecutables
38
+
39
+ `npm run examples` compila la librería y sirve [tres ejemplos independientes](./examples/README.md) en `http://localhost:5173/examples/`: tabla local, edición con validación y consulta simulada del servidor. Cada ejemplo importa las entradas públicas del paquete, igual que una aplicación consumidora.
40
+
41
+ ## Página de presentación
42
+
43
+ `npm run site` abre la página de presentación local. `npm run build:site` genera el sitio estático en `site-dist/`, separado de `dist/` para no incluirlo en el paquete npm. El workflow [Publish site](./.github/workflows/pages.yml) publica esa salida en GitHub Pages al cambiar el sitio o la librería en `main`. La configuración de Pages del repositorio debe usar **GitHub Actions** como fuente de publicación.
44
+
45
+ Consulta la [guía de publicación](./docs/PUBLICACION.md) para activar Pages y entender la diferencia entre Releases, GitHub Packages y npmjs.com.
46
+
47
+ ## Tabla con datos locales
48
+
49
+ Activa sólo las funciones que necesites. Las operaciones locales se aplican en este orden: **filtrar → ordenar → paginar**.
50
+
51
+ ```jsx
52
+ const columns = [
53
+ { field: 'name', headerName: 'Nombre', sortable: true, filterable: true },
54
+ { field: 'email', headerName: 'Correo' },
55
+ { field: 'internalId', hidden: true }
56
+ ];
57
+ const rows = [
58
+ { id: 1, name: 'Ana', email: 'ana@example.com', internalId: 'A1' },
59
+ { id: 2, name: 'Luis', email: 'luis@example.com', internalId: 'B2' }
60
+ ];
61
+
62
+ <Table
63
+ caption="Personas"
64
+ columns={columns}
65
+ rows={rows}
66
+ searchable
67
+ paginationEnabled
68
+ selectable
69
+ actions={[{ label: 'Ver', onClick: (row) => console.log(row) }]}
70
+ />;
71
+ ```
72
+
73
+ `sortable` en la tabla habilita todas las columnas; `sortable: true` en una columna habilita sólo esa columna. `sortable: false` la excluye aunque la tabla lo tenga activo. `filterable: true` añade un filtro de texto a la columna. La búsqueda global revisa las columnas visibles, salvo las que declaran `searchable: false`.
74
+
75
+ Para selección controlada:
76
+
77
+ ```jsx
78
+ const [selectedIds, setSelectedIds] = useState([]);
79
+ <Table
80
+ columns={columns}
81
+ rows={rows}
82
+ selectable
83
+ selectedRowIds={selectedIds}
84
+ onSelectionChange={(ids, loadedRows) => setSelectedIds(ids)}
85
+ />;
86
+ ```
87
+
88
+ La casilla del encabezado selecciona o deselecciona **la página visible**. Los IDs seleccionados de otras páginas permanecen. `loadedRows` contiene únicamente las filas seleccionadas presentes en `rows`; para acciones entre páginas remotas, usa `ids`.
89
+
90
+ ## Datos del servidor
91
+
92
+ Puedes controlar `sort`, `search`, `filters` y `pagination` desde React. Las opciones `manualSorting`, `manualFiltering` y `manualPagination` evitan que la librería vuelva a procesar filas que ya preparó el servidor. Usa `rowCount` para el total remoto.
93
+
94
+ ```jsx
95
+ function RemotePeople() {
96
+ const [rows, setRows] = useState([]);
97
+ const [rowCount, setRowCount] = useState(0);
98
+ const [sort, setSort] = useState(null);
99
+ const [search, setSearch] = useState('');
100
+ const [filters, setFilters] = useState({});
101
+ const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 10 });
102
+ const [loading, setLoading] = useState(false);
103
+ const [error, setError] = useState('');
104
+
105
+ useEffect(() => {
106
+ const controller = new AbortController();
107
+ const params = new URLSearchParams({
108
+ page: String(pagination.pageIndex + 1),
109
+ pageSize: String(pagination.pageSize),
110
+ search,
111
+ name: filters.name ?? '',
112
+ sortField: sort?.field ?? '',
113
+ sortDirection: sort?.direction ?? ''
114
+ });
115
+ setLoading(true);
116
+ setError('');
117
+ fetch(`/api/people?${params}`, { signal: controller.signal })
118
+ .then((response) => {
119
+ if (!response.ok) throw new Error('No se pudieron cargar las personas');
120
+ return response.json();
121
+ })
122
+ .then((data) => { setRows(data.rows); setRowCount(data.total); })
123
+ .catch((cause) => { if (cause.name !== 'AbortError') setError(cause.message); })
124
+ .finally(() => { if (!controller.signal.aborted) setLoading(false); });
125
+ return () => controller.abort();
126
+ }, [pagination, sort, search, filters]);
127
+
128
+ return <Table
129
+ columns={[{ field: 'name', headerName: 'Nombre', sortable: true, filterable: true }]}
130
+ rows={rows}
131
+ rowCount={rowCount}
132
+ loading={loading}
133
+ error={error}
134
+ searchable
135
+ paginationEnabled
136
+ manualSorting
137
+ manualFiltering
138
+ manualPagination
139
+ sort={sort}
140
+ onSortChange={setSort}
141
+ search={search}
142
+ onSearchChange={setSearch}
143
+ filters={filters}
144
+ onFiltersChange={setFilters}
145
+ pagination={pagination}
146
+ onPaginationChange={setPagination}
147
+ />;
148
+ }
149
+ ```
150
+
151
+ Los callbacks de búsqueda, filtros u ordenamiento solicitan volver a la primera página. Cuando `pagination` es controlada, proporciona `onPaginationChange` para aplicar ese cambio.
152
+
153
+ ## Edición
154
+
155
+ `TableEdit` tiene dos modos:
156
+
157
+ - `editMode="immediate"` (predeterminado): cada columna editable llama a `onChange(event, row)`; la aplicación actualiza `rows`. Conserva el comportamiento original.
158
+ - `editMode="save"`: la tabla mantiene un borrador por fila; muestra **Guardar** y **Cancelar** tras un cambio. `validate(value, draftRow)` devuelve un mensaje de error o un valor vacío. `onSave(draft, originalRow)` puede ser asíncrono. La aplicación debe actualizar `rows` al guardar.
159
+
160
+ ```jsx
161
+ function PeopleEditor() {
162
+ const [rows, setRows] = useState([{ id: 1, name: 'Ana', role: 'admin' }]);
163
+ const columns = [
164
+ {
165
+ field: 'name', headerName: 'Nombre', type: 'text',
166
+ validate: (value) => String(value ?? '').trim()
167
+ ? null : 'El nombre es obligatorio'
168
+ },
169
+ {
170
+ field: 'role', headerName: 'Rol', type: 'select',
171
+ options: [
172
+ { value: 'admin', label: 'Administrador' },
173
+ { value: 'viewer', label: 'Lector' }
174
+ ]
175
+ }
176
+ ];
177
+ const save = async (draft, original) => {
178
+ // También puedes enviar draft a tu API aquí.
179
+ setRows((current) => current.map((row) =>
180
+ row.id === original.id ? draft : row));
181
+ };
182
+ return <TableEdit columns={columns} rows={rows}
183
+ editMode="save" onSave={save} />;
184
+ }
185
+ ```
186
+
187
+ Los tipos de celda son `text`, `date`, `number`, `file`, `select` y `button`. Los valores de inputs llegan como cadenas, incluso con `type="number"`; conviértelos en tu callback si tu modelo necesita números. Para archivos, usa `event.target.files` en modo inmediato; en modo guardar, el borrador contiene el primer `File` o `null`. El input de archivo se limpia al cancelar o guardar.
188
+
189
+ `renderCell(value, row, rowIndex)` personaliza el contenido y tiene prioridad sobre `type`. Si implementas edición con `renderCell`, el control y sus cambios quedan a cargo de tu renderizador.
190
+
191
+ ## Referencia de props
192
+
193
+ | Prop | Tipo | Uso |
194
+ | --- | --- | --- |
195
+ | `columns` | `TableColumn[]` | Definición y orden de columnas. `field` debe ser único. |
196
+ | `rows` | `Row[]` | Filas recibidas de la aplicación. |
197
+ | `getRowId` | `(row, index) => string \| number` | ID estable; por defecto `row.id` y luego índice. |
198
+ | `caption` | `ReactNode` | Título semántico de la tabla. |
199
+ | `actions` | `TableAction[]` | Botones por fila; `onClick(row, event)`. |
200
+ | `searchable`, `search`, `onSearchChange` | `boolean`, `string`, función | Búsqueda global opcional/controlada. |
201
+ | `sortable`, `sort`, `onSortChange` | `boolean`, `{field, direction}`, función | Ordenamiento opcional/controlado. |
202
+ | `filters`, `onFiltersChange` | objeto, función | Filtros de columnas controlados. |
203
+ | `paginationEnabled`, `pagination`, `onPaginationChange` | `boolean`, `{pageIndex, pageSize}`, función | Paginación opcional/controlada; `pageIndex` empieza en 0. |
204
+ | `manualSorting`, `manualFiltering`, `manualPagination`, `rowCount` | booleanos, número | Operaciones delegadas al servidor. |
205
+ | `selectable`, `selectedRowIds`, `onSelectionChange` | `boolean`, IDs, función | Selección opcional/controlada. |
206
+ | `loading`, `error` | `boolean`, `ReactNode` | Estado de carga y aviso de error. |
207
+ | `emptyMessage`, `loadingMessage` | `ReactNode` | Textos de estado. |
208
+ | `className` | `string` | Clase adicional del contenedor. |
209
+
210
+ `TableEdit` también acepta `editMode`, `onSave`, `onCancel`, `saveLabel` y `cancelLabel`. Los textos de controles pueden adaptarse con `searchPlaceholder`, `actionsHeader`, `previousLabel`, `nextLabel` y `labels`:
211
+
212
+ ```jsx
213
+ <Table labels={{
214
+ search: 'Search table',
215
+ filter: (header) => `Filter ${header}`,
216
+ filterPlaceholder: 'Filter…',
217
+ selectPage: 'Select page',
218
+ selectRow: (id) => `Select row ${id}`,
219
+ rowsPerPage: 'Rows per page',
220
+ selectOption: 'Choose an option'
221
+ }} />
222
+ ```
223
+
224
+ Cada columna acepta `field`, `headerName`, `hidden`, `sortable`, `filterable`, `searchable`, `sortFn`, `filterFn`, `type`, `options`, `placeholder`, `renderCell`, `validate`, `onChange`, `onClick`, `label`, `icon`, `ariaLabel` y `style`. Cada acción acepta `id`, `label`, `icon`, `ariaLabel`, `className`, `style`, `disabled` y `onClick`. Si sólo muestra un icono, proporciona `ariaLabel`.
225
+
226
+ Los nombres anteriores `getColumns`, `getRows`, `getButtons` y `onCaption` siguen disponibles. En `TableEdit`, `getButtons` conserva `onClick(event, row)`; el prop nuevo `actions` usa `onClick(row, event)`. Si pasas ambas versiones, prevalece el nombre nuevo.
227
+
228
+ ## Diseño, accesibilidad y desarrollo
229
+
230
+ El estilo usa tipografía del sistema, separadores discretos, modo oscuro y foco visible. Sigue principios de las [Human Interface Guidelines para listas y tablas](https://developer.apple.com/design/human-interface-guidelines/lists-and-tables), [color](https://developer.apple.com/design/human-interface-guidelines/color) y [accesibilidad](https://developer.apple.com/design/human-interface-guidelines/accessibility). Es una implementación web inspirada en esas pautas, no un componente oficial de Apple.
231
+
232
+ Los encabezados anuncian el estado de ordenamiento con `aria-sort`; controles y errores tienen etiquetas; la carga y los cambios de página se anuncian. Los botones, inputs y casillas funcionan con teclado. En pantallas estrechas, la tabla se desplaza horizontalmente. Usa IDs estables para que selección y borradores sobrevivan al ordenamiento y la paginación.
233
+
234
+ El CSS sólo usa clases `.dt-*`. Personaliza `--dt-surface`, `--dt-surface-hover`, `--dt-text`, `--dt-secondary`, `--dt-separator`, `--dt-accent` y `--dt-on-accent` en el contenedor. `npm run build` genera ESM, CommonJS, tipos y CSS en `dist/`. React es una dependencia par y no se incluye en el paquete.
235
+
236
+ La matriz de CI ejecuta pruebas con React 18 y 19 sobre Node 22, 24 y 26. Las dependencias de desarrollo se fijan a versiones exactas en `package-lock.json`; el paquete publicado sólo exige React y React DOM como dependencias par.
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("react"),t=require("react/jsx-runtime");var n=e=>e==null?``:String(e);function r(e,t,r,i){let a=t.filter(e=>!e.hidden&&e.searchable!==!1),o=String(r??``).trim().toLocaleLowerCase();return e.filter(e=>o&&!a.some(t=>n(e[t.field]).toLocaleLowerCase().includes(o))?!1:Object.entries(i??{}).every(([r,i])=>{if(i==null||i===``)return!0;let a=t.find(e=>e.field===r);return a?a.filterFn?a.filterFn(e[r],i,e):n(e[r]).toLocaleLowerCase().includes(n(i).toLocaleLowerCase()):!0}))}function i(e,t,r){if(!t?.field||!t?.direction)return e;let i=r.find(e=>e.field===t.field);if(!i)return e;let a=t.direction===`desc`?-1:1,o=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});return e.map((e,t)=>({row:e,index:t})).sort((e,r)=>{let s=e.row[t.field],c=r.row[t.field];return s==null&&c==null?e.index-r.index:s==null?1:c==null?-1:(i.sortFn?i.sortFn(s,c,e.row,r.row):typeof s==`number`&&typeof c==`number`?s-c:o.compare(n(s),n(c)))*a||e.index-r.index}).map(({row:e})=>e)}function a(e,t,n){return e.slice(t*n,(t+1)*n)}var o=(e,t)=>e?.id??t,s={pageIndex:0,pageSize:10};function c({checked:e,mixed:n,onChange:r,label:i}){return(0,t.jsx)(`input`,{type:`checkbox`,checked:e,"aria-checked":n?`mixed`:e,"aria-label":i,onChange:r,ref:e=>{e&&(e.indeterminate=n)}})}function l({row:n,column:r,rowIndex:i,editable:a,saveMode:o,onEdit:s,error:c,errorId:l,disabled:u,fileVersion:d,selectOptionLabel:f}){let p=n?.[r.field];if(typeof r.renderCell==`function`)return r.renderCell(p,n,i);if(!a)return p??null;let m={name:r.field,"aria-label":r.headerName||r.field,"aria-invalid":!!c||void 0,"aria-describedby":c?l:void 0,disabled:u,onChange:e=>s(e,n,r)};return r.type===`button`?(0,t.jsxs)(`button`,{type:`button`,className:`dt-button`,style:r.style,"aria-label":r.ariaLabel??(typeof r.label==`string`?r.label:void 0),disabled:u,onClick:e=>r.onClick?.(e,n),children:[r.label,` `,r.icon]}):r.type===`select`?(0,t.jsxs)(`select`,{...m,className:`dt-control`,value:p??``,disabled:u||!o&&!r.onChange,children:[p==null&&(0,t.jsx)(`option`,{value:``,disabled:!0,children:r.placeholder??f}),(r.options??[]).map(e=>(0,t.jsx)(`option`,{value:e.value,children:e.label},String(e.value)))]}):[`text`,`date`,`number`,`file`].includes(r.type)?r.type===`file`?(0,e.createElement)(`input`,{...m,key:d,className:`dt-control`,type:`file`}):(0,t.jsx)(`input`,{...m,className:`dt-control`,type:r.type,value:p??``,readOnly:!o&&!r.onChange}):p??null}function u({columns:n=[],rows:u=[],actions:d=[],caption:f,editable:p=!1,legacyEditActions:m=!1,getRowId:h=o,actionsHeader:g=`Acciones`,emptyMessage:ee=`No hay datos`,className:te=``,sortable:ne=!1,sort:_,onSortChange:re,searchable:ie=!1,search:v,onSearchChange:ae,searchPlaceholder:oe=`Buscar…`,filters:y,onFiltersChange:se,paginationEnabled:ce=!1,pagination:b,onPaginationChange:le,manualSorting:ue=!1,manualFiltering:x=!1,manualPagination:S=!1,rowCount:de,selectable:C=!1,selectedRowIds:w,onSelectionChange:fe,loading:T=!1,error:pe,loadingMessage:me=`Cargando…`,editMode:he=`immediate`,onSave:E,onCancel:ge,previousLabel:_e=`Anterior`,nextLabel:ve=`Siguiente`,saveLabel:ye=`Guardar`,cancelLabel:be=`Cancelar`,labels:xe={}}){let D={search:`Buscar en la tabla`,filter:e=>`Filtrar ${e}`,filterPlaceholder:`Filtrar…`,selectPage:`Seleccionar página`,selectRow:e=>`Seleccionar fila ${e}`,rowsPerPage:`Filas por página`,selectOption:`Selecciona una opción`,...xe},[Se,Ce]=(0,e.useState)(null),[we,Te]=(0,e.useState)(``),[Ee,De]=(0,e.useState)({}),[Oe,ke]=(0,e.useState)(s),[Ae,je]=(0,e.useState)([]),[O,k]=(0,e.useState)({}),[Me,A]=(0,e.useState)({}),[Ne,j]=(0,e.useState)({}),[M,N]=(0,e.useState)({}),[Pe,Fe]=(0,e.useState)({}),Ie=(0,e.useId)().replace(/:/g,``),P=_===void 0?Se:_,F=v===void 0?we:v,I=y===void 0?Ee:y,L=b??Oe,R=w===void 0?Ae:w,z=p&&he===`save`,B=n.filter(e=>!e.hidden),V=Array.isArray(d)?d:[],H=V.length>0||z,Le=ie||v!==void 0,U=ce||b!==void 0,Re=B.length+ +!!C+ +!!H,W=(0,e.useMemo)(()=>{let e=x?u:r(u,n,F,I);return ue?e:i(e,P,n)},[u,n,F,I,P,x,ue]),G=S?de??u.length:W.length,K=Math.max(1,Number(L.pageSize)||10),ze=Math.max(0,Math.ceil(G/K)-1),q=Math.max(0,Math.min(Number(L.pageIndex)||0,ze)),J=U&&!S?a(W,q,K):W,Y=new Set(R.map(String)),X=J.map((e,t)=>h(e,t)),Z=X.filter(e=>Y.has(String(e))).length,Q=e=>{let t={pageIndex:Math.max(0,e.pageIndex),pageSize:e.pageSize};b===void 0&&ke(t),le?.(t)},$=()=>{U&&q!==0&&Q({pageIndex:0,pageSize:K})},Be=e=>{let t={field:e.field,direction:P?.field===e.field&&P.direction===`asc`?`desc`:`asc`};_===void 0&&Ce(t),re?.(t),$()},Ve=e=>{v===void 0&&Te(e),ae?.(e),$()},He=(e,t)=>{let n={...I,[e]:t};y===void 0&&De(n),se?.(n),$()},Ue=e=>{w===void 0&&je(e),fe?.(e,u.filter((t,n)=>e.some(e=>String(e)===String(h(t,n)))))},We=()=>{let e=X.length>0&&Z===X.length?R.filter(e=>!X.some(t=>String(t)===String(e))):[...R,...X.filter(e=>!Y.has(String(e)))];Ue(e)},Ge=(e,t,n,r)=>{if(!z){n.onChange?.(e,t);return}let i=n.type===`file`?e.target.files?.[0]??null:e.target.value,a=String(r),o={...t,...O[a],[n.field]:i};if(k(e=>({...e,[a]:o})),N(e=>({...e,[a]:``})),n.validate){let e=n.validate(i,o)||``;A(t=>({...t,[a]:{...t[a],[n.field]:e}}))}},Ke=e=>{k(t=>{let n={...t};return delete n[e],n}),A(t=>{let n={...t};return delete n[e],n}),N(t=>{let n={...t};return delete n[e],n}),Fe(t=>({...t,[e]:(t[e]??0)+1}))},qe=async(e,t)=>{let r=String(e),i=O[r];if(!i||!E)return;let a={};for(let e of n)if(e.validate){let t=e.validate(i[e.field],i);t&&(a[e.field]=t)}if(Object.keys(a).length)A(e=>({...e,[r]:a}));else{j(e=>({...e,[r]:!0}));try{await E(i,t),Ke(r)}catch(e){N(t=>({...t,[r]:e?.message||`No se pudo guardar`}))}finally{j(e=>({...e,[r]:!1}))}}};return(0,t.jsxs)(`div`,{className:`dt-container ${te}`.trim(),children:[Le&&(0,t.jsx)(`div`,{className:`dt-toolbar`,children:(0,t.jsxs)(`label`,{className:`dt-search-label`,children:[(0,t.jsx)(`span`,{className:`dt-visually-hidden`,children:D.search}),(0,t.jsx)(`input`,{className:`dt-control dt-search`,type:`search`,value:F??``,placeholder:oe,onChange:e=>Ve(e.target.value)})]})}),pe&&(0,t.jsx)(`div`,{className:`dt-message dt-error`,role:`alert`,children:pe}),(0,t.jsx)(`div`,{className:`dt-scroll`,children:(0,t.jsxs)(`table`,{className:`dt-table`,"aria-busy":T,children:[f&&(0,t.jsx)(`caption`,{children:f}),(0,t.jsxs)(`thead`,{children:[(0,t.jsxs)(`tr`,{children:[C&&(0,t.jsx)(`th`,{scope:`col`,className:`dt-selection`,children:(0,t.jsx)(c,{checked:X.length>0&&Z===X.length,mixed:Z>0&&Z<X.length,onChange:We,label:D.selectPage})}),B.map(e=>{let n=(ne||e.sortable)&&e.sortable!==!1,r=P?.field===e.field?P.direction:null;return(0,t.jsx)(`th`,{scope:`col`,"aria-sort":r===`asc`?`ascending`:r===`desc`?`descending`:void 0,children:n?(0,t.jsxs)(`button`,{type:`button`,className:`dt-sort`,onClick:()=>Be(e),children:[e.headerName??e.field,(0,t.jsx)(`span`,{"aria-hidden":`true`,className:`dt-sort-icon`,children:r===`asc`?`↑`:r===`desc`?`↓`:`↕`})]}):e.headerName??e.field},e.field)}),H&&(0,t.jsx)(`th`,{scope:`col`,children:g})]}),B.some(e=>e.filterable)&&(0,t.jsxs)(`tr`,{className:`dt-filter-row`,children:[C&&(0,t.jsx)(`th`,{role:`presentation`}),B.map(e=>(0,t.jsx)(`th`,{role:`presentation`,children:e.filterable&&(0,t.jsx)(`input`,{className:`dt-control`,type:`search`,"aria-label":D.filter(e.headerName??e.field),value:I[e.field]??``,placeholder:D.filterPlaceholder,onChange:t=>He(e.field,t.target.value)})},e.field)),H&&(0,t.jsx)(`th`,{role:`presentation`})]})]}),(0,t.jsx)(`tbody`,{children:T?(0,t.jsx)(`tr`,{children:(0,t.jsx)(`td`,{className:`dt-empty`,colSpan:Math.max(Re,1),role:`status`,children:me})}):J.length===0?(0,t.jsx)(`tr`,{children:(0,t.jsx)(`td`,{className:`dt-empty`,colSpan:Math.max(Re,1),children:ee})}):J.map((e,n)=>{let r=h(e,n),i=String(r),a=z?O[i]??e:e,o=!!Ne[i];return(0,t.jsxs)(`tr`,{"aria-selected":C?Y.has(i):void 0,children:[C&&(0,t.jsx)(`td`,{className:`dt-selection`,children:(0,t.jsx)(`input`,{type:`checkbox`,checked:Y.has(i),"aria-label":D.selectRow(r),onChange:()=>Ue(Y.has(i)?R.filter(e=>String(e)!==i):[...R,r])})}),B.map(s=>{let c=Me[i]?.[s.field],u=`${Ie}-${i}-${s.field}`;return(0,t.jsxs)(`td`,{"data-label":s.headerName??s.field,children:[l({row:a,column:s,rowIndex:n,editable:p,saveMode:z,error:c,errorId:u,disabled:o,fileVersion:Pe[i]??0,selectOptionLabel:D.selectOption,onEdit:t=>Ge(t,e,s,r)}),c&&(0,t.jsx)(`span`,{className:`dt-field-error`,id:u,children:c})]},s.field)}),H&&(0,t.jsxs)(`td`,{"data-label":g,children:[(0,t.jsxs)(`div`,{className:`dt-actions`,children:[V.map((n,r)=>(0,t.jsxs)(`button`,{type:`button`,className:`dt-button ${n.className??``}`.trim(),style:n.style,disabled:o||n.disabled,"aria-label":n.ariaLabel??(typeof n.label==`string`?n.label:void 0),onClick:t=>m?n.onClick?.(t,e):n.onClick?.(e,t),children:[n.label,` `,n.icon]},n.id??r)),z&&O[i]&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(`button`,{type:`button`,className:`dt-button dt-primary`,disabled:o||!E,onClick:()=>qe(r,e),children:o?me:ye}),(0,t.jsx)(`button`,{type:`button`,className:`dt-button`,disabled:o,onClick:()=>{Ke(i),ge?.(e)},children:be})]})]}),M[i]&&(0,t.jsx)(`span`,{className:`dt-field-error`,role:`alert`,children:M[i]})]})]},r)})})]})}),U&&(0,t.jsxs)(`div`,{className:`dt-pagination`,children:[(0,t.jsxs)(`span`,{"aria-live":`polite`,children:[G===0?`0`:q*K+1,`–`,Math.min((q+1)*K,G),` de `,G]}),(0,t.jsxs)(`div`,{className:`dt-page-actions`,children:[(0,t.jsxs)(`label`,{children:[D.rowsPerPage,(0,t.jsx)(`select`,{className:`dt-control`,value:K,onChange:e=>Q({pageIndex:0,pageSize:Number(e.target.value)}),children:[10,25,50,100].includes(K)?[10,25,50,100].map(e=>(0,t.jsx)(`option`,{value:e,children:e},e)):[K,10,25,50,100].map(e=>(0,t.jsx)(`option`,{value:e,children:e},e))})]}),(0,t.jsx)(`button`,{type:`button`,className:`dt-button`,disabled:q===0||T,onClick:()=>Q({pageIndex:q-1,pageSize:K}),children:_e}),(0,t.jsx)(`button`,{type:`button`,className:`dt-button`,disabled:q>=ze||T,onClick:()=>Q({pageIndex:q+1,pageSize:K}),children:ve})]})]})]})}function d({getColumns:e,getRows:n,getButtons:r,onCaption:i,...a}){return(0,t.jsx)(u,{...a,columns:a.columns??e??[],rows:a.rows??n??[],actions:a.actions??r??[],caption:a.caption??i})}function f({getColumns:e,getRows:n,getButtons:r,onCaption:i,...a}){return(0,t.jsx)(u,{...a,editable:!0,columns:a.columns??e??[],rows:a.rows??n??[],actions:a.actions??r??[],legacyEditActions:a.actions==null&&r!=null,caption:a.caption??i})}exports.Table=d,exports.TableEdit=f;
@@ -0,0 +1,103 @@
1
+ import type { CSSProperties, ReactNode, ChangeEvent, MouseEvent } from 'react';
2
+
3
+ export type TableRow = object;
4
+ export interface TableOption { value: string | number; label: ReactNode }
5
+ export interface TableColumn<Row extends TableRow = TableRow> {
6
+ field: string;
7
+ headerName?: string;
8
+ hidden?: boolean;
9
+ sortable?: boolean;
10
+ filterable?: boolean;
11
+ searchable?: boolean;
12
+ type?: 'text' | 'date' | 'number' | 'file' | 'select' | 'button';
13
+ options?: TableOption[];
14
+ placeholder?: string;
15
+ label?: ReactNode;
16
+ ariaLabel?: string;
17
+ icon?: ReactNode;
18
+ style?: CSSProperties;
19
+ renderCell?: (value: unknown, row: Row, rowIndex: number) => ReactNode;
20
+ sortFn?: (left: unknown, right: unknown, leftRow: Row, rightRow: Row) => number;
21
+ filterFn?: (value: unknown, filter: string, row: Row) => boolean;
22
+ validate?: (value: unknown, row: Row) => string | null | undefined;
23
+ onChange?: (event: ChangeEvent<HTMLInputElement | HTMLSelectElement>, row: Row) => void;
24
+ onClick?: (event: MouseEvent<HTMLButtonElement>, row: Row) => void;
25
+ }
26
+ export interface TableAction<Row extends TableRow = TableRow> {
27
+ id?: string | number;
28
+ label?: ReactNode;
29
+ icon?: ReactNode;
30
+ ariaLabel?: string;
31
+ className?: string;
32
+ style?: CSSProperties;
33
+ disabled?: boolean;
34
+ onClick?: (row: Row, event: MouseEvent<HTMLButtonElement>) => void;
35
+ }
36
+ export interface LegacyEditAction<Row extends TableRow = TableRow>
37
+ extends Omit<TableAction<Row>, 'onClick'> {
38
+ onClick?: (event: MouseEvent<HTMLButtonElement>, row: Row) => void;
39
+ }
40
+ export interface TableSort { field: string; direction: 'asc' | 'desc' }
41
+ export interface TablePagination { pageIndex: number; pageSize: number }
42
+ export interface TableLabels {
43
+ search?: string;
44
+ filter?: (header: string) => string;
45
+ filterPlaceholder?: string;
46
+ selectPage?: string;
47
+ selectRow?: (id: string | number) => string;
48
+ rowsPerPage?: string;
49
+ selectOption?: string;
50
+ }
51
+ interface BaseProps<Row extends TableRow> {
52
+ columns?: TableColumn<Row>[];
53
+ rows?: Row[];
54
+ actions?: TableAction<Row>[];
55
+ caption?: ReactNode;
56
+ actionsHeader?: ReactNode;
57
+ getRowId?: (row: Row, index: number) => string | number;
58
+ emptyMessage?: ReactNode;
59
+ className?: string;
60
+ sortable?: boolean;
61
+ sort?: TableSort | null;
62
+ onSortChange?: (sort: TableSort) => void;
63
+ searchable?: boolean;
64
+ search?: string;
65
+ onSearchChange?: (search: string) => void;
66
+ searchPlaceholder?: string;
67
+ filters?: Record<string, string>;
68
+ onFiltersChange?: (filters: Record<string, string>) => void;
69
+ paginationEnabled?: boolean;
70
+ pagination?: TablePagination;
71
+ onPaginationChange?: (pagination: TablePagination) => void;
72
+ manualSorting?: boolean;
73
+ manualFiltering?: boolean;
74
+ manualPagination?: boolean;
75
+ rowCount?: number;
76
+ selectable?: boolean;
77
+ selectedRowIds?: Array<string | number>;
78
+ onSelectionChange?: (ids: Array<string | number>, loadedRows: Row[]) => void;
79
+ loading?: boolean;
80
+ error?: ReactNode;
81
+ loadingMessage?: ReactNode;
82
+ previousLabel?: string;
83
+ nextLabel?: string;
84
+ labels?: TableLabels;
85
+ getColumns?: TableColumn<Row>[];
86
+ getRows?: Row[];
87
+ onCaption?: ReactNode;
88
+ }
89
+ export interface TableProps<Row extends TableRow = TableRow> extends BaseProps<Row> {
90
+ /** Legacy alias of actions. */
91
+ getButtons?: TableAction<Row>[];
92
+ }
93
+ export interface TableEditProps<Row extends TableRow = TableRow> extends BaseProps<Row> {
94
+ editMode?: 'immediate' | 'save';
95
+ onSave?: (draft: Row, originalRow: Row) => void | Promise<void>;
96
+ onCancel?: (originalRow: Row) => void;
97
+ saveLabel?: string;
98
+ cancelLabel?: string;
99
+ /** Legacy edit actions receive (event, row). Prefer actions, which receive (row, event). */
100
+ getButtons?: LegacyEditAction<Row>[];
101
+ }
102
+ export declare function Table<Row extends TableRow = TableRow>(props: TableProps<Row>): ReactNode;
103
+ export declare function TableEdit<Row extends TableRow = TableRow>(props: TableEditProps<Row>): ReactNode;
package/dist/index.js ADDED
@@ -0,0 +1,490 @@
1
+ import { createElement as e, useId as t, useMemo as n, useState as r } from "react";
2
+ import { Fragment as i, jsx as a, jsxs as o } from "react/jsx-runtime";
3
+ // src/rowModel.js
4
+ var s = (e) => e == null ? "" : String(e);
5
+ function c(e, t, n, r) {
6
+ let i = t.filter((e) => !e.hidden && e.searchable !== !1), a = String(n ?? "").trim().toLocaleLowerCase();
7
+ return e.filter((e) => a && !i.some((t) => s(e[t.field]).toLocaleLowerCase().includes(a)) ? !1 : Object.entries(r ?? {}).every(([n, r]) => {
8
+ if (r == null || r === "") return !0;
9
+ let i = t.find((e) => e.field === n);
10
+ return i ? i.filterFn ? i.filterFn(e[n], r, e) : s(e[n]).toLocaleLowerCase().includes(s(r).toLocaleLowerCase()) : !0;
11
+ }));
12
+ }
13
+ function l(e, t, n) {
14
+ if (!t?.field || !t?.direction) return e;
15
+ let r = n.find((e) => e.field === t.field);
16
+ if (!r) return e;
17
+ let i = t.direction === "desc" ? -1 : 1, a = new Intl.Collator(void 0, {
18
+ numeric: !0,
19
+ sensitivity: "base"
20
+ });
21
+ return e.map((e, t) => ({
22
+ row: e,
23
+ index: t
24
+ })).sort((e, n) => {
25
+ let o = e.row[t.field], c = n.row[t.field];
26
+ return o == null && c == null ? e.index - n.index : o == null ? 1 : c == null ? -1 : (r.sortFn ? r.sortFn(o, c, e.row, n.row) : typeof o == "number" && typeof c == "number" ? o - c : a.compare(s(o), s(c))) * i || e.index - n.index;
27
+ }).map(({ row: e }) => e);
28
+ }
29
+ function u(e, t, n) {
30
+ return e.slice(t * n, (t + 1) * n);
31
+ }
32
+ // src/TableBase.jsx
33
+ var d = (e, t) => e?.id ?? t, ee = {
34
+ pageIndex: 0,
35
+ pageSize: 10
36
+ };
37
+ function f({ checked: e, mixed: t, onChange: n, label: r }) {
38
+ return /* @__PURE__ */ a("input", {
39
+ type: "checkbox",
40
+ checked: e,
41
+ "aria-checked": t ? "mixed" : e,
42
+ "aria-label": r,
43
+ onChange: n,
44
+ ref: (e) => {
45
+ e && (e.indeterminate = t);
46
+ }
47
+ });
48
+ }
49
+ function p({ row: t, column: n, rowIndex: r, editable: i, saveMode: s, onEdit: c, error: l, errorId: u, disabled: d, fileVersion: ee, selectOptionLabel: f }) {
50
+ let p = t?.[n.field];
51
+ if (typeof n.renderCell == "function") return n.renderCell(p, t, r);
52
+ if (!i) return p ?? null;
53
+ let m = {
54
+ name: n.field,
55
+ "aria-label": n.headerName || n.field,
56
+ "aria-invalid": !!l || void 0,
57
+ "aria-describedby": l ? u : void 0,
58
+ disabled: d,
59
+ onChange: (e) => c(e, t, n)
60
+ };
61
+ return n.type === "button" ? /* @__PURE__ */ o("button", {
62
+ type: "button",
63
+ className: "dt-button",
64
+ style: n.style,
65
+ "aria-label": n.ariaLabel ?? (typeof n.label == "string" ? n.label : void 0),
66
+ disabled: d,
67
+ onClick: (e) => n.onClick?.(e, t),
68
+ children: [
69
+ n.label,
70
+ " ",
71
+ n.icon
72
+ ]
73
+ }) : n.type === "select" ? /* @__PURE__ */ o("select", {
74
+ ...m,
75
+ className: "dt-control",
76
+ value: p ?? "",
77
+ disabled: d || !s && !n.onChange,
78
+ children: [p == null && /* @__PURE__ */ a("option", {
79
+ value: "",
80
+ disabled: !0,
81
+ children: n.placeholder ?? f
82
+ }), (n.options ?? []).map((e) => /* @__PURE__ */ a("option", {
83
+ value: e.value,
84
+ children: e.label
85
+ }, String(e.value)))]
86
+ }) : [
87
+ "text",
88
+ "date",
89
+ "number",
90
+ "file"
91
+ ].includes(n.type) ? n.type === "file" ? /* @__PURE__ */ e("input", {
92
+ ...m,
93
+ key: ee,
94
+ className: "dt-control",
95
+ type: "file"
96
+ }) : /* @__PURE__ */ a("input", {
97
+ ...m,
98
+ className: "dt-control",
99
+ type: n.type,
100
+ value: p ?? "",
101
+ readOnly: !s && !n.onChange
102
+ }) : p ?? null;
103
+ }
104
+ function m({ columns: e = [], rows: s = [], actions: m = [], caption: h, editable: g = !1, legacyEditActions: te = !1, getRowId: _ = d, actionsHeader: v = "Acciones", emptyMessage: ne = "No hay datos", className: re = "", sortable: ie = !1, sort: y, onSortChange: ae, searchable: oe = !1, search: b, onSearchChange: se, searchPlaceholder: ce = "Buscar…", filters: x, onFiltersChange: le, paginationEnabled: ue = !1, pagination: S, onPaginationChange: de, manualSorting: C = !1, manualFiltering: fe = !1, manualPagination: pe = !1, rowCount: me, selectable: w = !1, selectedRowIds: T, onSelectionChange: he, loading: E = !1, error: ge, loadingMessage: _e = "Cargando…", editMode: ve = "immediate", onSave: D, onCancel: ye, previousLabel: be = "Anterior", nextLabel: xe = "Siguiente", saveLabel: Se = "Guardar", cancelLabel: Ce = "Cancelar", labels: we = {} }) {
105
+ let O = {
106
+ search: "Buscar en la tabla",
107
+ filter: (e) => `Filtrar ${e}`,
108
+ filterPlaceholder: "Filtrar…",
109
+ selectPage: "Seleccionar página",
110
+ selectRow: (e) => `Seleccionar fila ${e}`,
111
+ rowsPerPage: "Filas por página",
112
+ selectOption: "Selecciona una opción",
113
+ ...we
114
+ }, [Te, Ee] = r(null), [De, Oe] = r(""), [ke, Ae] = r({}), [je, Me] = r(ee), [Ne, Pe] = r([]), [k, A] = r({}), [Fe, j] = r({}), [Ie, M] = r({}), [N, P] = r({}), [Le, Re] = r({}), ze = t().replace(/:/g, ""), F = y === void 0 ? Te : y, I = b === void 0 ? De : b, L = x === void 0 ? ke : x, Be = S ?? je, R = T === void 0 ? Ne : T, z = g && ve === "save", B = e.filter((e) => !e.hidden), Ve = Array.isArray(m) ? m : [], V = Ve.length > 0 || z, He = oe || b !== void 0, H = ue || S !== void 0, Ue = B.length + +!!w + +!!V, U = n(() => {
115
+ let t = fe ? s : c(s, e, I, L);
116
+ return C ? t : l(t, F, e);
117
+ }, [
118
+ s,
119
+ e,
120
+ I,
121
+ L,
122
+ F,
123
+ fe,
124
+ C
125
+ ]), W = pe ? me ?? s.length : U.length, G = Math.max(1, Number(Be.pageSize) || 10), We = Math.max(0, Math.ceil(W / G) - 1), K = Math.max(0, Math.min(Number(Be.pageIndex) || 0, We)), q = H && !pe ? u(U, K, G) : U, J = new Set(R.map(String)), Y = q.map((e, t) => _(e, t)), X = Y.filter((e) => J.has(String(e))).length, Z = (e) => {
126
+ let t = {
127
+ pageIndex: Math.max(0, e.pageIndex),
128
+ pageSize: e.pageSize
129
+ };
130
+ S === void 0 && Me(t), de?.(t);
131
+ }, Q = () => {
132
+ H && K !== 0 && Z({
133
+ pageIndex: 0,
134
+ pageSize: G
135
+ });
136
+ }, Ge = (e) => {
137
+ let t = {
138
+ field: e.field,
139
+ direction: F?.field === e.field && F.direction === "asc" ? "desc" : "asc"
140
+ };
141
+ y === void 0 && Ee(t), ae?.(t), Q();
142
+ }, Ke = (e) => {
143
+ b === void 0 && Oe(e), se?.(e), Q();
144
+ }, qe = (e, t) => {
145
+ let n = {
146
+ ...L,
147
+ [e]: t
148
+ };
149
+ x === void 0 && Ae(n), le?.(n), Q();
150
+ }, Je = (e) => {
151
+ T === void 0 && Pe(e), he?.(e, s.filter((t, n) => e.some((e) => String(e) === String(_(t, n)))));
152
+ }, Ye = () => {
153
+ let e = Y.length > 0 && X === Y.length ? R.filter((e) => !Y.some((t) => String(t) === String(e))) : [...R, ...Y.filter((e) => !J.has(String(e)))];
154
+ Je(e);
155
+ }, Xe = (e, t, n, r) => {
156
+ if (!z) {
157
+ n.onChange?.(e, t);
158
+ return;
159
+ }
160
+ let i = n.type === "file" ? e.target.files?.[0] ?? null : e.target.value, a = String(r), o = {
161
+ ...t,
162
+ ...k[a],
163
+ [n.field]: i
164
+ };
165
+ if (A((e) => ({
166
+ ...e,
167
+ [a]: o
168
+ })), P((e) => ({
169
+ ...e,
170
+ [a]: ""
171
+ })), n.validate) {
172
+ let e = n.validate(i, o) || "";
173
+ j((t) => ({
174
+ ...t,
175
+ [a]: {
176
+ ...t[a],
177
+ [n.field]: e
178
+ }
179
+ }));
180
+ }
181
+ }, $ = (e) => {
182
+ A((t) => {
183
+ let n = { ...t };
184
+ return delete n[e], n;
185
+ }), j((t) => {
186
+ let n = { ...t };
187
+ return delete n[e], n;
188
+ }), P((t) => {
189
+ let n = { ...t };
190
+ return delete n[e], n;
191
+ }), Re((t) => ({
192
+ ...t,
193
+ [e]: (t[e] ?? 0) + 1
194
+ }));
195
+ }, Ze = async (t, n) => {
196
+ let r = String(t), i = k[r];
197
+ if (!i || !D) return;
198
+ let a = {};
199
+ for (let t of e) if (t.validate) {
200
+ let e = t.validate(i[t.field], i);
201
+ e && (a[t.field] = e);
202
+ }
203
+ if (Object.keys(a).length) j((e) => ({
204
+ ...e,
205
+ [r]: a
206
+ }));
207
+ else {
208
+ M((e) => ({
209
+ ...e,
210
+ [r]: !0
211
+ }));
212
+ try {
213
+ await D(i, n), $(r);
214
+ } catch (e) {
215
+ P((t) => ({
216
+ ...t,
217
+ [r]: e?.message || "No se pudo guardar"
218
+ }));
219
+ } finally {
220
+ M((e) => ({
221
+ ...e,
222
+ [r]: !1
223
+ }));
224
+ }
225
+ }
226
+ };
227
+ return /* @__PURE__ */ o("div", {
228
+ className: `dt-container ${re}`.trim(),
229
+ children: [
230
+ He && /* @__PURE__ */ a("div", {
231
+ className: "dt-toolbar",
232
+ children: /* @__PURE__ */ o("label", {
233
+ className: "dt-search-label",
234
+ children: [/* @__PURE__ */ a("span", {
235
+ className: "dt-visually-hidden",
236
+ children: O.search
237
+ }), /* @__PURE__ */ a("input", {
238
+ className: "dt-control dt-search",
239
+ type: "search",
240
+ value: I ?? "",
241
+ placeholder: ce,
242
+ onChange: (e) => Ke(e.target.value)
243
+ })]
244
+ })
245
+ }),
246
+ ge && /* @__PURE__ */ a("div", {
247
+ className: "dt-message dt-error",
248
+ role: "alert",
249
+ children: ge
250
+ }),
251
+ /* @__PURE__ */ a("div", {
252
+ className: "dt-scroll",
253
+ children: /* @__PURE__ */ o("table", {
254
+ className: "dt-table",
255
+ "aria-busy": E,
256
+ children: [
257
+ h && /* @__PURE__ */ a("caption", { children: h }),
258
+ /* @__PURE__ */ o("thead", { children: [/* @__PURE__ */ o("tr", { children: [
259
+ w && /* @__PURE__ */ a("th", {
260
+ scope: "col",
261
+ className: "dt-selection",
262
+ children: /* @__PURE__ */ a(f, {
263
+ checked: Y.length > 0 && X === Y.length,
264
+ mixed: X > 0 && X < Y.length,
265
+ onChange: Ye,
266
+ label: O.selectPage
267
+ })
268
+ }),
269
+ B.map((e) => {
270
+ let t = (ie || e.sortable) && e.sortable !== !1, n = F?.field === e.field ? F.direction : null;
271
+ return /* @__PURE__ */ a("th", {
272
+ scope: "col",
273
+ "aria-sort": n === "asc" ? "ascending" : n === "desc" ? "descending" : void 0,
274
+ children: t ? /* @__PURE__ */ o("button", {
275
+ type: "button",
276
+ className: "dt-sort",
277
+ onClick: () => Ge(e),
278
+ children: [e.headerName ?? e.field, /* @__PURE__ */ a("span", {
279
+ "aria-hidden": "true",
280
+ className: "dt-sort-icon",
281
+ children: n === "asc" ? "↑" : n === "desc" ? "↓" : "↕"
282
+ })]
283
+ }) : e.headerName ?? e.field
284
+ }, e.field);
285
+ }),
286
+ V && /* @__PURE__ */ a("th", {
287
+ scope: "col",
288
+ children: v
289
+ })
290
+ ] }), B.some((e) => e.filterable) && /* @__PURE__ */ o("tr", {
291
+ className: "dt-filter-row",
292
+ children: [
293
+ w && /* @__PURE__ */ a("th", { role: "presentation" }),
294
+ B.map((e) => /* @__PURE__ */ a("th", {
295
+ role: "presentation",
296
+ children: e.filterable && /* @__PURE__ */ a("input", {
297
+ className: "dt-control",
298
+ type: "search",
299
+ "aria-label": O.filter(e.headerName ?? e.field),
300
+ value: L[e.field] ?? "",
301
+ placeholder: O.filterPlaceholder,
302
+ onChange: (t) => qe(e.field, t.target.value)
303
+ })
304
+ }, e.field)),
305
+ V && /* @__PURE__ */ a("th", { role: "presentation" })
306
+ ]
307
+ })] }),
308
+ /* @__PURE__ */ a("tbody", { children: E ? /* @__PURE__ */ a("tr", { children: /* @__PURE__ */ a("td", {
309
+ className: "dt-empty",
310
+ colSpan: Math.max(Ue, 1),
311
+ role: "status",
312
+ children: _e
313
+ }) }) : q.length === 0 ? /* @__PURE__ */ a("tr", { children: /* @__PURE__ */ a("td", {
314
+ className: "dt-empty",
315
+ colSpan: Math.max(Ue, 1),
316
+ children: ne
317
+ }) }) : q.map((e, t) => {
318
+ let n = _(e, t), r = String(n), s = z ? k[r] ?? e : e, c = !!Ie[r];
319
+ return /* @__PURE__ */ o("tr", {
320
+ "aria-selected": w ? J.has(r) : void 0,
321
+ children: [
322
+ w && /* @__PURE__ */ a("td", {
323
+ className: "dt-selection",
324
+ children: /* @__PURE__ */ a("input", {
325
+ type: "checkbox",
326
+ checked: J.has(r),
327
+ "aria-label": O.selectRow(n),
328
+ onChange: () => Je(J.has(r) ? R.filter((e) => String(e) !== r) : [...R, n])
329
+ })
330
+ }),
331
+ B.map((i) => {
332
+ let l = Fe[r]?.[i.field], u = `${ze}-${r}-${i.field}`;
333
+ return /* @__PURE__ */ o("td", {
334
+ "data-label": i.headerName ?? i.field,
335
+ children: [p({
336
+ row: s,
337
+ column: i,
338
+ rowIndex: t,
339
+ editable: g,
340
+ saveMode: z,
341
+ error: l,
342
+ errorId: u,
343
+ disabled: c,
344
+ fileVersion: Le[r] ?? 0,
345
+ selectOptionLabel: O.selectOption,
346
+ onEdit: (t) => Xe(t, e, i, n)
347
+ }), l && /* @__PURE__ */ a("span", {
348
+ className: "dt-field-error",
349
+ id: u,
350
+ children: l
351
+ })]
352
+ }, i.field);
353
+ }),
354
+ V && /* @__PURE__ */ o("td", {
355
+ "data-label": v,
356
+ children: [/* @__PURE__ */ o("div", {
357
+ className: "dt-actions",
358
+ children: [Ve.map((t, n) => /* @__PURE__ */ o("button", {
359
+ type: "button",
360
+ className: `dt-button ${t.className ?? ""}`.trim(),
361
+ style: t.style,
362
+ disabled: c || t.disabled,
363
+ "aria-label": t.ariaLabel ?? (typeof t.label == "string" ? t.label : void 0),
364
+ onClick: (n) => te ? t.onClick?.(n, e) : t.onClick?.(e, n),
365
+ children: [
366
+ t.label,
367
+ " ",
368
+ t.icon
369
+ ]
370
+ }, t.id ?? n)), z && k[r] && /* @__PURE__ */ o(i, { children: [/* @__PURE__ */ a("button", {
371
+ type: "button",
372
+ className: "dt-button dt-primary",
373
+ disabled: c || !D,
374
+ onClick: () => Ze(n, e),
375
+ children: c ? _e : Se
376
+ }), /* @__PURE__ */ a("button", {
377
+ type: "button",
378
+ className: "dt-button",
379
+ disabled: c,
380
+ onClick: () => {
381
+ $(r), ye?.(e);
382
+ },
383
+ children: Ce
384
+ })] })]
385
+ }), N[r] && /* @__PURE__ */ a("span", {
386
+ className: "dt-field-error",
387
+ role: "alert",
388
+ children: N[r]
389
+ })]
390
+ })
391
+ ]
392
+ }, n);
393
+ }) })
394
+ ]
395
+ })
396
+ }),
397
+ H && /* @__PURE__ */ o("div", {
398
+ className: "dt-pagination",
399
+ children: [/* @__PURE__ */ o("span", {
400
+ "aria-live": "polite",
401
+ children: [
402
+ W === 0 ? "0" : K * G + 1,
403
+ "–",
404
+ Math.min((K + 1) * G, W),
405
+ " de ",
406
+ W
407
+ ]
408
+ }), /* @__PURE__ */ o("div", {
409
+ className: "dt-page-actions",
410
+ children: [
411
+ /* @__PURE__ */ o("label", { children: [O.rowsPerPage, /* @__PURE__ */ a("select", {
412
+ className: "dt-control",
413
+ value: G,
414
+ onChange: (e) => Z({
415
+ pageIndex: 0,
416
+ pageSize: Number(e.target.value)
417
+ }),
418
+ children: [
419
+ 10,
420
+ 25,
421
+ 50,
422
+ 100
423
+ ].includes(G) ? [
424
+ 10,
425
+ 25,
426
+ 50,
427
+ 100
428
+ ].map((e) => /* @__PURE__ */ a("option", {
429
+ value: e,
430
+ children: e
431
+ }, e)) : [
432
+ G,
433
+ 10,
434
+ 25,
435
+ 50,
436
+ 100
437
+ ].map((e) => /* @__PURE__ */ a("option", {
438
+ value: e,
439
+ children: e
440
+ }, e))
441
+ })] }),
442
+ /* @__PURE__ */ a("button", {
443
+ type: "button",
444
+ className: "dt-button",
445
+ disabled: K === 0 || E,
446
+ onClick: () => Z({
447
+ pageIndex: K - 1,
448
+ pageSize: G
449
+ }),
450
+ children: be
451
+ }),
452
+ /* @__PURE__ */ a("button", {
453
+ type: "button",
454
+ className: "dt-button",
455
+ disabled: K >= We || E,
456
+ onClick: () => Z({
457
+ pageIndex: K + 1,
458
+ pageSize: G
459
+ }),
460
+ children: xe
461
+ })
462
+ ]
463
+ })]
464
+ })
465
+ ]
466
+ });
467
+ }
468
+ // src/Table.jsx
469
+ function h({ getColumns: e, getRows: t, getButtons: n, onCaption: r, ...i }) {
470
+ return /* @__PURE__ */ a(m, {
471
+ ...i,
472
+ columns: i.columns ?? e ?? [],
473
+ rows: i.rows ?? t ?? [],
474
+ actions: i.actions ?? n ?? [],
475
+ caption: i.caption ?? r
476
+ });
477
+ }
478
+ // src/TableEdit.jsx
479
+ function g({ getColumns: e, getRows: t, getButtons: n, onCaption: r, ...i }) {
480
+ return /* @__PURE__ */ a(m, {
481
+ ...i,
482
+ editable: !0,
483
+ columns: i.columns ?? e ?? [],
484
+ rows: i.rows ?? t ?? [],
485
+ actions: i.actions ?? n ?? [],
486
+ legacyEditActions: i.actions == null && n != null,
487
+ caption: i.caption ?? r
488
+ });
489
+ }
490
+ export { h as Table, g as TableEdit };
package/dist/style.css ADDED
@@ -0,0 +1,2 @@
1
+ .dt-container{--dt-surface:#fff;--dt-surface-hover:#f7f7f9;--dt-text:#1d1d1f;--dt-secondary:#6e6e73;--dt-separator:#e5e5e7;--dt-accent:#06c;--dt-on-accent:#fff;color:var(--dt-text);background:var(--dt-surface);border:1px solid var(--dt-separator);-webkit-overflow-scrolling:touch;border-radius:12px;font:400 14px/1.45 -apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;overflow:hidden}.dt-scroll{-webkit-overflow-scrolling:touch;overflow-x:auto}.dt-table{border-collapse:collapse;text-align:left;width:100%;min-width:28rem}.dt-table caption{text-align:left;padding:16px 18px;font-size:17px;font-weight:600}.dt-table th,.dt-table td{border-bottom:1px solid var(--dt-separator);vertical-align:middle;padding:11px 18px}.dt-table thead th{color:var(--dt-secondary);letter-spacing:.01em;white-space:nowrap;font-size:12px;font-weight:600}.dt-table tbody tr:last-child td{border-bottom:0}.dt-table tbody tr:hover{background:var(--dt-surface-hover)}.dt-table tbody tr[aria-selected=true]{background:color-mix(in srgb, var(--dt-accent) 10%, var(--dt-surface))}.dt-empty{color:var(--dt-secondary);text-align:center;padding:24px 18px!important}.dt-actions{flex-wrap:wrap;align-items:center;gap:8px;display:flex}.dt-button,.dt-control{border:1px solid var(--dt-separator);background:var(--dt-surface);min-height:36px;color:var(--dt-text);font:inherit;border-radius:8px}.dt-button{cursor:pointer;white-space:nowrap;padding:6px 12px;font-weight:500}.dt-button:hover{background:var(--dt-surface-hover)}.dt-button:active{transform:scale(.98)}.dt-button:disabled{cursor:not-allowed;opacity:.5}.dt-control{box-sizing:border-box;width:100%;min-width:8rem;padding:6px 9px}.dt-button:focus-visible,.dt-control:focus-visible{outline:3px solid var(--dt-accent);outline-offset:2px}.dt-toolbar{border-bottom:1px solid var(--dt-separator);padding:12px 16px}.dt-search-label{width:min(100%,22rem);display:block}.dt-search{width:100%}.dt-sort{color:inherit;font:inherit;cursor:pointer;background:0 0;border:0;align-items:center;gap:7px;padding:4px 0;font-weight:600;display:inline-flex}.dt-sort:hover{color:var(--dt-text)}.dt-sort:focus-visible{outline:3px solid var(--dt-accent);outline-offset:3px;border-radius:2px}.dt-sort-icon{color:var(--dt-secondary);font-size:15px}.dt-filter-row th{padding-top:0}.dt-filter-row .dt-control{min-width:7rem;font-size:13px}.dt-selection{text-align:center;width:42px}.dt-selection input{width:18px;height:18px;accent-color:var(--dt-accent);cursor:pointer;margin:0}.dt-selection input:focus-visible{outline:3px solid var(--dt-accent);outline-offset:3px}.dt-primary{background:var(--dt-accent);color:var(--dt-on-accent);border-color:var(--dt-accent)}.dt-primary:hover{background:var(--dt-accent);filter:brightness(.93)}.dt-field-error{color:#c72833;margin-top:5px;font-size:12px;display:block}.dt-control[aria-invalid=true]{border-color:#c72833}.dt-message{padding:12px 16px}.dt-error{color:#a11e2a;background:#fff1f1}.dt-pagination{border-top:1px solid var(--dt-separator);color:var(--dt-secondary);justify-content:space-between;align-items:center;gap:12px;padding:12px 16px;font-size:13px;display:flex}.dt-page-actions,.dt-page-actions label{align-items:center;gap:8px;display:flex}.dt-page-actions .dt-control{width:auto;min-width:4rem}.dt-visually-hidden{clip:rect(0, 0, 0, 0);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}@media (width<=640px){.dt-pagination,.dt-page-actions{flex-wrap:wrap}.dt-table th,.dt-table td{padding:10px 12px}}@media (prefers-color-scheme:dark){.dt-container{--dt-surface:#1c1c1e;--dt-surface-hover:#2c2c2e;--dt-text:#f5f5f7;--dt-secondary:#aeaeb2;--dt-separator:#3a3a3c;--dt-accent:#0a84ff;--dt-on-accent:#000}.dt-field-error{color:#ff6961}.dt-error{color:#ffb4b0;background:#3b171a}}@media (prefers-reduced-motion:reduce){.dt-button:active{transform:none}}
2
+ /*$vite$:1*/
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@isai_dev/data_table_lib",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "Accessible React tables with editable cells and row actions",
5
+ "author": {
6
+ "name": "Jaziel Isaí",
7
+ "url": "https://isai-dev.com"
8
+ },
9
+ "license": "MIT",
10
+ "homepage": "https://jazielisai.github.io/data_table_lib/",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/JazielIsai/data_table_lib.git"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "type": "module",
19
+ "main": "./dist/index.cjs",
20
+ "module": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js",
26
+ "require": "./dist/index.cjs"
27
+ },
28
+ "./style.css": "./dist/style.css"
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "sideEffects": [
34
+ "*.css"
35
+ ],
36
+ "scripts": {
37
+ "start": "vite",
38
+ "presite": "npm run build",
39
+ "site": "vite --config vite.site.config.js",
40
+ "build:site": "npm run build && vite build --config vite.site.config.js",
41
+ "preexamples": "npm run build",
42
+ "examples": "vite",
43
+ "build": "node scripts/build.mjs",
44
+ "test": "npm run build && tsc --noEmit -p tsconfig.types.json && node --test tests/*.test.mjs",
45
+ "typecheck": "npm run build && tsc --noEmit -p tsconfig.types.json",
46
+ "prepack": "npm run build"
47
+ },
48
+ "peerDependencies": {
49
+ "react": "^18.0.0 || ^19.0.0",
50
+ "react-dom": "^18.0.0 || ^19.0.0"
51
+ },
52
+ "devDependencies": {
53
+ "@testing-library/react": "16.3.3",
54
+ "@types/react": "19.3.0",
55
+ "@types/react-dom": "19.3.0",
56
+ "jsdom": "31.0.1",
57
+ "react": "19.3.1",
58
+ "react-dom": "19.3.1",
59
+ "typescript": "7.0.2",
60
+ "vite": "8.3.8"
61
+ }
62
+ }