@easyvision/easyvision-ui 1.3.4
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/README.md +1391 -0
- package/dist/EasyVisionTable.css +68 -0
- package/dist/easyvision.css +30 -0
- package/dist/index.cjs +2968 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +612 -0
- package/dist/index.d.ts +612 -0
- package/dist/index.js +2929 -0
- package/dist/index.js.map +1 -0
- package/package.json +64 -0
package/README.md
ADDED
|
@@ -0,0 +1,1391 @@
|
|
|
1
|
+
# EasyVision
|
|
2
|
+
|
|
3
|
+
A small, shadcn-backed component set for building filtered, paginated, sortable views with as little plumbing as possible. Each component owns its own state via an internal zustand registry — the user only supplies an `id`.
|
|
4
|
+
|
|
5
|
+
```tsx
|
|
6
|
+
import {
|
|
7
|
+
EasyVisionInput,
|
|
8
|
+
EasyVisionSelector,
|
|
9
|
+
EasyVisionMultifilter,
|
|
10
|
+
EasyVisionTable,
|
|
11
|
+
} from '@/components/easyvision';
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## Table of contents
|
|
17
|
+
|
|
18
|
+
- [Core concepts](#core-concepts)
|
|
19
|
+
- [The `id` rule](#the-id-rule)
|
|
20
|
+
- [Persistence and cleanup](#persistence-and-cleanup)
|
|
21
|
+
- [`clearWhen`](#clearwhen)
|
|
22
|
+
- [Labels (i18n)](#labels-i18n)
|
|
23
|
+
- [`EasyVisionCard`](#easyvisioncard)
|
|
24
|
+
- [`EasyVisionInput`](#easyvisioninput)
|
|
25
|
+
- [`EasyVisionSelector`](#easyvisionselector)
|
|
26
|
+
- [`EasyVisionMultifilter`](#easyvisionmultifilter)
|
|
27
|
+
- [Field types](#field-types)
|
|
28
|
+
- [Pinned, chip, locked](#pinned-chip-locked)
|
|
29
|
+
- [Buscar (perform) button](#buscar-perform-button)
|
|
30
|
+
- [Standalone usage (no table)](#standalone-usage-no-table)
|
|
31
|
+
- [Nesting](#nesting)
|
|
32
|
+
- [Snapshot shape](#snapshot-shape)
|
|
33
|
+
- [`EasyVisionTable`](#easyvisiontable)
|
|
34
|
+
- [Choosing a data + filter strategy](#choosing-a-data--filter-strategy)
|
|
35
|
+
- [Local vs API mode](#local-vs-api-mode)
|
|
36
|
+
- [Column definitions](#column-definitions)
|
|
37
|
+
- [Column sizing, truncation, and resizing](#column-sizing-truncation-and-resizing)
|
|
38
|
+
- [Body height & sticky header](#body-height--sticky-header)
|
|
39
|
+
- [Selection](#selection)
|
|
40
|
+
- [Highlighting rows (master/detail)](#highlighting-rows-masterdetail)
|
|
41
|
+
- [Binding a multifilter](#binding-a-multifilter)
|
|
42
|
+
- [External filter and manual refetch](#external-filter-and-manual-refetch)
|
|
43
|
+
- [Toolbar slots](#toolbar-slots)
|
|
44
|
+
- [Migration cookbook](#migration-cookbook)
|
|
45
|
+
- [Integration recipes](#integration-recipes)
|
|
46
|
+
- [API adapters: LoopBack](#api-adapters-loopback)
|
|
47
|
+
- [Local mode filtering with the same DSL — `matchLoopbackWhere`](#local-mode-filtering-with-the-same-dsl--matchloopbackwhere)
|
|
48
|
+
- [Gotchas](#gotchas)
|
|
49
|
+
- [Escape hatch: direct registry access](#escape-hatch-direct-registry-access)
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## Core concepts
|
|
54
|
+
|
|
55
|
+
### The `id` rule
|
|
56
|
+
|
|
57
|
+
Every stateful component takes a required `id: string`. Internally that becomes a key in the registry: `${id}-${componentKind}`, e.g. `myFilter-multifilter`, `userTable-table`.
|
|
58
|
+
|
|
59
|
+
When a component is declared inside another (a Selector field inside a Multifilter, a Multifilter bound to a Table), only the **outer** id is needed — children inherit the namespace and append their own local id. Example:
|
|
60
|
+
|
|
61
|
+
```tsx
|
|
62
|
+
<EasyVisionTable
|
|
63
|
+
id="riskEvals" // riskEvals-table
|
|
64
|
+
multifilter={{
|
|
65
|
+
id: 'mainFilter', // riskEvals-table.mainFilter-multifilter
|
|
66
|
+
config: { fields: [
|
|
67
|
+
{ id: 'level', type: 'selector', /*...*/ } // riskEvals-table.mainFilter-multifilter.level value
|
|
68
|
+
]},
|
|
69
|
+
}}
|
|
70
|
+
/>
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Pick `id`s that are stable across renders. They don't have to be globally unique — the namespace tree disambiguates them.
|
|
74
|
+
|
|
75
|
+
### Persistence and cleanup
|
|
76
|
+
|
|
77
|
+
Every component is **non-persistent by default**: when it unmounts, its slice (and every descendant slice) is dropped from the registry. To keep state across mount/unmount cycles, set `persist={true}`.
|
|
78
|
+
|
|
79
|
+
```tsx
|
|
80
|
+
<EasyVisionMultifilter id="alerts" persist config={...} />
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Because the registry is a single zustand-vanilla store, you can inspect state at any time:
|
|
84
|
+
|
|
85
|
+
```tsx
|
|
86
|
+
import { easyVisionRegistry } from '@/components/easyvision';
|
|
87
|
+
|
|
88
|
+
console.log(easyVisionRegistry.getState().slices);
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### `clearWhen`
|
|
92
|
+
|
|
93
|
+
Pass a predicate that receives the current snapshot/value. When it returns `true`, the slice is dropped and re-initialized from defaults. Useful for "reset filters when the parent entity changes":
|
|
94
|
+
|
|
95
|
+
```tsx
|
|
96
|
+
<EasyVisionInput
|
|
97
|
+
id="search"
|
|
98
|
+
clearWhen={(value) => parentId !== lastParentIdRef.current}
|
|
99
|
+
/>
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Labels (i18n)
|
|
103
|
+
|
|
104
|
+
Components ship with Spanish defaults (`Buscar`, `Resultados por página`, etc.). All user-visible strings can be overridden via the `labels` prop, which takes a `Partial<Labels>`:
|
|
105
|
+
|
|
106
|
+
```tsx
|
|
107
|
+
<EasyVisionTable
|
|
108
|
+
labels={{ rowsPerPage: t('table.rows'), of: t('common.of') }}
|
|
109
|
+
/* ... */
|
|
110
|
+
/>
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
To plug into a `react-i18next` (or any other) translation system, just pass `t(...)` calls in the `labels` object.
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## `EasyVisionCard`
|
|
118
|
+
|
|
119
|
+
Self-contained card primitive shared by every EasyVision surface (the
|
|
120
|
+
Multifilter container is one). Mirrors the Shadcn Card API but lives inside
|
|
121
|
+
the library, so projects consuming EasyVision don't need to install or
|
|
122
|
+
maintain a separate `ui/card` component. Visuals rely only on the standard
|
|
123
|
+
Tailwind theme tokens (`bg-card`, `text-card-foreground`, `border`,
|
|
124
|
+
`shadow-sm`) the host project already exposes.
|
|
125
|
+
|
|
126
|
+
It's a **purely presentational, stateless** component — no `id`, no slice,
|
|
127
|
+
no persistence. Use it anywhere you'd otherwise hand-roll
|
|
128
|
+
`<div className="bg-card border border-border rounded-md shadow-sm">`.
|
|
129
|
+
|
|
130
|
+
### Sub-components
|
|
131
|
+
|
|
132
|
+
All sub-components are **independent and optional**. Compose only what you
|
|
133
|
+
need; nothing enforces ordering or presence.
|
|
134
|
+
|
|
135
|
+
| Component | Element | Default classes | Purpose |
|
|
136
|
+
|---|---|---|---|
|
|
137
|
+
| `EasyVisionCard` | `div` | `rounded-md border bg-card text-card-foreground shadow-sm` | Outer container. |
|
|
138
|
+
| `EasyVisionCardHeader` | `div` | `flex flex-col space-y-1.5 p-6` | Vertical stack for title + description. |
|
|
139
|
+
| `EasyVisionCardTitle` | `h3` | `text-2xl font-semibold leading-none tracking-tight` | Heading inside the header. |
|
|
140
|
+
| `EasyVisionCardDescription` | `p` | `text-sm text-muted-foreground` | Subtitle under the title. |
|
|
141
|
+
| `EasyVisionCardContent` | `div` | `p-6 pt-0` | Main body. |
|
|
142
|
+
| `EasyVisionCardFooter` | `div` | `flex items-center p-6 pt-0` | Action row at the bottom. |
|
|
143
|
+
|
|
144
|
+
### Minimal usage
|
|
145
|
+
|
|
146
|
+
Just the container — what the Multifilter does internally:
|
|
147
|
+
|
|
148
|
+
```tsx
|
|
149
|
+
<EasyVisionCard className="p-3">
|
|
150
|
+
{/* anything */}
|
|
151
|
+
</EasyVisionCard>
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### Full composition
|
|
155
|
+
|
|
156
|
+
```tsx
|
|
157
|
+
import {
|
|
158
|
+
EasyVisionCard,
|
|
159
|
+
EasyVisionCardHeader,
|
|
160
|
+
EasyVisionCardTitle,
|
|
161
|
+
EasyVisionCardDescription,
|
|
162
|
+
EasyVisionCardContent,
|
|
163
|
+
EasyVisionCardFooter,
|
|
164
|
+
} from '@/components/easyvision';
|
|
165
|
+
|
|
166
|
+
<EasyVisionCard>
|
|
167
|
+
<EasyVisionCardHeader>
|
|
168
|
+
<EasyVisionCardTitle>Risk evaluations</EasyVisionCardTitle>
|
|
169
|
+
<EasyVisionCardDescription>Last 30 days</EasyVisionCardDescription>
|
|
170
|
+
</EasyVisionCardHeader>
|
|
171
|
+
<EasyVisionCardContent>
|
|
172
|
+
<EasyVisionTable id="riskEvals" /* ... */ />
|
|
173
|
+
</EasyVisionCardContent>
|
|
174
|
+
<EasyVisionCardFooter>
|
|
175
|
+
<Button>Export</Button>
|
|
176
|
+
</EasyVisionCardFooter>
|
|
177
|
+
</EasyVisionCard>
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### Notes
|
|
181
|
+
|
|
182
|
+
- All components forward `ref` and accept any standard HTML attributes.
|
|
183
|
+
- `className` is **merged** with the defaults, not replaced — pass
|
|
184
|
+
`className="p-3"` to override padding without losing the border/shadow.
|
|
185
|
+
- Skip the header entirely if you don't need a title; the body padding
|
|
186
|
+
comes from `EasyVisionCardContent` (`p-6 pt-0`) — when there's no header,
|
|
187
|
+
use `<EasyVisionCardContent className="pt-6">` or just put your content
|
|
188
|
+
in a plain wrapper.
|
|
189
|
+
|
|
190
|
+
---
|
|
191
|
+
|
|
192
|
+
## `EasyVisionInput`
|
|
193
|
+
|
|
194
|
+
A debounced text input that persists its value by `id`.
|
|
195
|
+
|
|
196
|
+
### Minimal usage
|
|
197
|
+
|
|
198
|
+
```tsx
|
|
199
|
+
<EasyVisionInput
|
|
200
|
+
id="searchClients"
|
|
201
|
+
placeholder="Buscar..."
|
|
202
|
+
icon="search"
|
|
203
|
+
onChange={(value) => console.log(value)}
|
|
204
|
+
/>
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Props
|
|
208
|
+
|
|
209
|
+
| prop | type | default | notes |
|
|
210
|
+
|---|---|---|---|
|
|
211
|
+
| `id` | `string` | — | Required. Slice key. |
|
|
212
|
+
| `label` | `string` | — | Renders above the input. |
|
|
213
|
+
| `placeholder` | `string` | — | |
|
|
214
|
+
| `debounceMs` | `number` | `300` | Time of inactivity before `onChange` fires. |
|
|
215
|
+
| `mandatory` | `boolean` | `false` | Adds red asterisk; reports invalid to a parent multifilter for Buscar gating. |
|
|
216
|
+
| `defaultValue` | `string` | `''` | Used on first mount only. |
|
|
217
|
+
| `onChange` | `(value: string) => void` | — | Fires with the **debounced** value. |
|
|
218
|
+
| `icon` | `'search' \| 'none'` | `'none'` | |
|
|
219
|
+
| `showClearButton` | `boolean` | `false` | Adds an inline X. |
|
|
220
|
+
| `disabled` | `boolean` | `false` | |
|
|
221
|
+
| `className` | `string` | — | |
|
|
222
|
+
| `persist` | `boolean` | `false` | Keep state across unmount. |
|
|
223
|
+
| `clearWhen` | `(value) => boolean` | — | Reset the slice when this returns `true`. |
|
|
224
|
+
| `onStateChange` | `(value) => void` | — | Fires on every change (no debounce). |
|
|
225
|
+
|
|
226
|
+
---
|
|
227
|
+
|
|
228
|
+
## `EasyVisionSelector`
|
|
229
|
+
|
|
230
|
+
Single-select dropdown. Supports `searchable` (cmdk-backed combobox) and `confirmMode` (commit on button press).
|
|
231
|
+
|
|
232
|
+
### Minimal usage
|
|
233
|
+
|
|
234
|
+
```tsx
|
|
235
|
+
<EasyVisionSelector
|
|
236
|
+
id="country"
|
|
237
|
+
label="País"
|
|
238
|
+
options={[
|
|
239
|
+
{ value: 'ES', label: 'España' },
|
|
240
|
+
{ value: 'FR', label: 'Francia' },
|
|
241
|
+
]}
|
|
242
|
+
onChange={(v) => console.log(v)}
|
|
243
|
+
/>
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
### Async options
|
|
247
|
+
|
|
248
|
+
```tsx
|
|
249
|
+
<EasyVisionSelector
|
|
250
|
+
id="sector"
|
|
251
|
+
options={async () => fetch('/api/sectors').then(r => r.json())}
|
|
252
|
+
/>
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
### Searchable + mandatory
|
|
256
|
+
|
|
257
|
+
```tsx
|
|
258
|
+
<EasyVisionSelector
|
|
259
|
+
id="risk"
|
|
260
|
+
searchable
|
|
261
|
+
mandatory
|
|
262
|
+
options={riskOptions}
|
|
263
|
+
/>
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
### Props
|
|
267
|
+
|
|
268
|
+
| prop | type | default | notes |
|
|
269
|
+
|---|---|---|---|
|
|
270
|
+
| `id` | `string` | — | Required. |
|
|
271
|
+
| `label` | `string` | — | |
|
|
272
|
+
| `options` | `Array<{value, label}>` or `() => Promise<Array<...>>` | — | Sync or async. |
|
|
273
|
+
| `placeholder` | `string` | `'Seleccionar...'` | |
|
|
274
|
+
| `mandatory` | `boolean` | `false` | Forces a value; affects parent multifilter Buscar gating. |
|
|
275
|
+
| `defaultValue` | `string \| number` | — | |
|
|
276
|
+
| `confirmMode` | `boolean` | `false` | Renders a Confirm button; value isn't committed until pressed. |
|
|
277
|
+
| `confirmLabel` | `string` | `'Confirmar'` | Label for the confirm button. |
|
|
278
|
+
| `searchable` | `boolean` | `false` | Switches to a Combobox with text search. |
|
|
279
|
+
| `onChange` | `(value) => void` | — | Fires with the committed value. |
|
|
280
|
+
| `disabled`, `className`, `persist`, `clearWhen`, `onStateChange` | as in Input | | |
|
|
281
|
+
|
|
282
|
+
---
|
|
283
|
+
|
|
284
|
+
## `EasyVisionMultifilter`
|
|
285
|
+
|
|
286
|
+
A composable filter row: pinned (always-visible) area + dynamic chips area + optional Buscar button. Supports nested multifilters.
|
|
287
|
+
|
|
288
|
+
### Minimal usage
|
|
289
|
+
|
|
290
|
+
```tsx
|
|
291
|
+
<EasyVisionMultifilter
|
|
292
|
+
id="alertsFilter"
|
|
293
|
+
performButton
|
|
294
|
+
onPerform={(snap) => fetchAlerts(snap.query)}
|
|
295
|
+
config={{
|
|
296
|
+
fields: [
|
|
297
|
+
{ id: 'q', type: 'text', field: 'name', label: 'Búsqueda', prominent: true, pinned: true },
|
|
298
|
+
{ id: 'level', type: 'multiselect', field: 'level', label: 'Nivel', pinned: true, mandatory: true,
|
|
299
|
+
options: [{value:'CRITICAL', label:'Crítico'}, {value:'HIGH', label:'Alto'}] },
|
|
300
|
+
{ id: 'status', type: 'selector', field: 'status', label: 'Estado', pinned: true,
|
|
301
|
+
options: [{value:'pending', label:'Pendiente'}, {value:'completed', label:'Completado'}] },
|
|
302
|
+
{ id: 'dates', type: 'dateRange', field: 'created', label: 'Fechas' },
|
|
303
|
+
],
|
|
304
|
+
}}
|
|
305
|
+
/>
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
### Prominent fields (the top search bar)
|
|
309
|
+
|
|
310
|
+
Any `type: 'text'` field with `prominent: true` renders **full-width at the top of the panel** with a magnifying-glass icon, instead of as an inline chip. Pressing **Enter** inside a prominent field triggers the Buscar action. The flag is orthogonal to `pinned`/`initiallyActive`, so any combination works:
|
|
311
|
+
|
|
312
|
+
| `prominent` | `pinned` | `initiallyActive` | behaviour |
|
|
313
|
+
|---|---|---|---|
|
|
314
|
+
| `true` | `true` | — | Permanent big bar (most common — replaces the legacy `searchField`). |
|
|
315
|
+
| `true` | `false` | `true` | Big bar that the user can detach with the X and re-add from the `+` menu. |
|
|
316
|
+
| `true` | `false` | `false` | Hidden by default. Appears as a big bar once added from the `+` menu. |
|
|
317
|
+
| `false` | any | any | Renders as an inline chip (default). |
|
|
318
|
+
|
|
319
|
+
Multiple prominent fields are allowed and wrap onto extra rows as needed.
|
|
320
|
+
|
|
321
|
+
> **Legacy:** `config.searchField` is kept as a deprecated alias and behaves like a virtual prominent + pinned text field. Prefer `prominent: true, pinned: true` in `fields` for new code so there's a single mental model — *everything is a field*.
|
|
322
|
+
|
|
323
|
+
### Field types
|
|
324
|
+
|
|
325
|
+
Each entry in `config.fields` is one of:
|
|
326
|
+
|
|
327
|
+
| `type` | renders | value shape |
|
|
328
|
+
|---|---|---|
|
|
329
|
+
| `'text'` | inline text input chip | `string` |
|
|
330
|
+
| `'selector'` | inline dropdown chip | `string \| number` |
|
|
331
|
+
| `'multiselect'` | tag-pill chip with popover checkboxes | `(string \| number)[]` |
|
|
332
|
+
| `'dateRange'` | date-range popover chip | `{ from?: Date; to?: Date }` |
|
|
333
|
+
| `'numberRange'` | min/max pair chip | `{ min?: number; max?: number }` |
|
|
334
|
+
| `'multifilter'` | nested filter box (see [Nesting](#nesting)) | `{ values: ..., activeFields: ... }` |
|
|
335
|
+
| `'custom'` | your own component (`definition.component`) | whatever you store |
|
|
336
|
+
|
|
337
|
+
Common base fields on every field def:
|
|
338
|
+
|
|
339
|
+
```ts
|
|
340
|
+
{
|
|
341
|
+
id: string; // local id
|
|
342
|
+
label: string; // shown next to the chip
|
|
343
|
+
field?: string; // API path used to build the where clause; e.g. 'client.country'
|
|
344
|
+
pinned?: boolean; // always rendered (locked-in)
|
|
345
|
+
initiallyActive?: boolean; // for non-pinned fields, show by default on first mount
|
|
346
|
+
locked?: boolean; // suppress X chip but keep the field active
|
|
347
|
+
mandatory?: boolean; // gates Buscar
|
|
348
|
+
visible?: boolean | ((values) => boolean); // conditional visibility
|
|
349
|
+
defaultValue?: unknown;
|
|
350
|
+
placeholder?: string;
|
|
351
|
+
toCondition?: (value) => unknown; // override the where-clause builder for this field
|
|
352
|
+
}
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
### Pinned, chip, locked
|
|
356
|
+
|
|
357
|
+
- **`pinned: true`** — always rendered in the pinned row, never has an X chip, never appears in the "+" popover.
|
|
358
|
+
- **`locked: true`** (and not pinned) — appears in the chip area but cannot be removed.
|
|
359
|
+
- **default** (neither flag) — appears under the "+" popover until added; once added, gets an X chip to remove.
|
|
360
|
+
|
|
361
|
+
To make the multifilter fully static (no `+`, no X), set `editable={false}` on the multifilter itself:
|
|
362
|
+
|
|
363
|
+
```tsx
|
|
364
|
+
<EasyVisionMultifilter editable={false} config={...} />
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
### Buscar (perform) button
|
|
368
|
+
|
|
369
|
+
> **Terminology.** "Perform" is the generic name for "user committed the filter" — i.e. the **Buscar / Search** action. It's called `perform` (not `onSearch`) because the multifilter is generic: the same event can drive a list refetch, an export, a recalculation, a navigation. The default button label is `"Buscar"`; override via `performLabel`.
|
|
370
|
+
|
|
371
|
+
Set `performButton={true}` and an `onPerform` callback. The button's enable state combines:
|
|
372
|
+
|
|
373
|
+
- `editable !== false` — the multifilter must be active.
|
|
374
|
+
- `isValid` — every `mandatory` field has a non-empty value (recursively, including nested multifilters).
|
|
375
|
+
- `isDirty` — the snapshot differs from the last confirmation (or, if never confirmed, has at least one non-empty value).
|
|
376
|
+
|
|
377
|
+
After press, dirty resets to `false`; editing back to the confirmed state re-disables the button.
|
|
378
|
+
|
|
379
|
+
```tsx
|
|
380
|
+
<EasyVisionMultifilter
|
|
381
|
+
id="alerts"
|
|
382
|
+
performButton
|
|
383
|
+
performLabel="Buscar" // default; localize as needed
|
|
384
|
+
performPosition="inline" // 'inline' | 'belowRow' | 'externalRef'
|
|
385
|
+
performOnMount // fire once if persisted state has values
|
|
386
|
+
onPerform={(snap) => api.list(snap.query)}
|
|
387
|
+
config={...}
|
|
388
|
+
/>
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
You can also call perform programmatically via a ref:
|
|
392
|
+
|
|
393
|
+
```tsx
|
|
394
|
+
const ref = useRef<MultifilterHandle>(null);
|
|
395
|
+
// ...
|
|
396
|
+
<EasyVisionMultifilter ref={ref} {...} />
|
|
397
|
+
// ref.current?.perform();
|
|
398
|
+
// ref.current?.getSnapshot();
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
### Standalone usage (no table)
|
|
402
|
+
|
|
403
|
+
Nothing about the multifilter is table-specific — it's a generic, persisted, validated form-snapshot component. Use it on its own to drive a chart, a KPI panel, an export, a URL query, or any other consumer.
|
|
404
|
+
|
|
405
|
+
Declarative — `onPerform` runs your action when the user clicks Buscar (and once on mount when `performOnMount` is set):
|
|
406
|
+
|
|
407
|
+
```tsx
|
|
408
|
+
const [kpis, setKpis] = useState<Kpis | null>(null);
|
|
409
|
+
|
|
410
|
+
<EasyVisionMultifilter
|
|
411
|
+
id="kpisFilters"
|
|
412
|
+
persist
|
|
413
|
+
config={filterConfig}
|
|
414
|
+
performButton
|
|
415
|
+
performOnMount
|
|
416
|
+
onPerform={(snap) =>
|
|
417
|
+
fetchKpisByFilter({ where: snap.query.where ?? {} }).then(setKpis)
|
|
418
|
+
}
|
|
419
|
+
/>
|
|
420
|
+
<KpiPanel data={kpis} />
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
Imperative — drive the multifilter from outside via the ref handle. Useful for parent buttons, route changes, or wizard flows:
|
|
424
|
+
|
|
425
|
+
```tsx
|
|
426
|
+
const mfRef = useRef<MultifilterHandle>(null);
|
|
427
|
+
|
|
428
|
+
<EasyVisionMultifilter ref={mfRef} id="..." config={...} />
|
|
429
|
+
|
|
430
|
+
// Read the current snapshot (e.g. to mirror into the URL):
|
|
431
|
+
const snap = mfRef.current?.getSnapshot();
|
|
432
|
+
|
|
433
|
+
// Force a perform from outside (e.g. a global "Apply" button):
|
|
434
|
+
mfRef.current?.perform();
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
The handle exposes `{ perform, getSnapshot }`. The same `MultifilterSnapshot` shape applies whether the multifilter is bound to a table or standing alone — see [Snapshot shape](#snapshot-shape).
|
|
438
|
+
|
|
439
|
+
### Nesting
|
|
440
|
+
|
|
441
|
+
Declare a child multifilter as a field of type `'multifilter'`:
|
|
442
|
+
|
|
443
|
+
```tsx
|
|
444
|
+
{
|
|
445
|
+
id: 'clientFilter',
|
|
446
|
+
type: 'multifilter',
|
|
447
|
+
label: 'Cliente avanzado',
|
|
448
|
+
pinned: false,
|
|
449
|
+
config: {
|
|
450
|
+
fields: [
|
|
451
|
+
{ id: 'sector', type: 'selector', field: 'client.sector', label: 'Sector', options: sectorOptions },
|
|
452
|
+
{ id: 'country', type: 'selector', field: 'client.country', label: 'País', options: countryOptions },
|
|
453
|
+
],
|
|
454
|
+
},
|
|
455
|
+
}
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
The child's slice id is derived (`parent.fullId.${childId}-multifilter`). The parent's snapshot includes the child's values under the field id, and the child's mandatory/dirty states bubble up. The root owns the Buscar button by default; setting `performButton: true` on a nested config gives that section its own Apply button which only confirms its own snapshot (the table-level Buscar still belongs to the root).
|
|
459
|
+
|
|
460
|
+
### Snapshot shape
|
|
461
|
+
|
|
462
|
+
Every `onChange` and `onPerform` receives:
|
|
463
|
+
|
|
464
|
+
```ts
|
|
465
|
+
interface MultifilterSnapshot {
|
|
466
|
+
values: Record<string, unknown>; // includes nested multifilter values as nested objects
|
|
467
|
+
activeFields: string[]; // visible field ids in display order
|
|
468
|
+
isValid: boolean; // every mandatory has non-empty value
|
|
469
|
+
isDirty: boolean; // differs from last confirmation
|
|
470
|
+
query: {
|
|
471
|
+
where?: Record<string, unknown>; // built API filter clause
|
|
472
|
+
order?: string[];
|
|
473
|
+
limit?: number;
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
The default `query.where` builder uses these conventions per type:
|
|
479
|
+
- `text` → `{ [field]: { $regex: `.*${value}.*`, $options: 'i' } }`
|
|
480
|
+
- `selector` → `{ [field]: value }`
|
|
481
|
+
- `multiselect` → `{ [field]: { $in: value } }`
|
|
482
|
+
- `dateRange` → `{ [field]: { $gte, $lte } }` (ISO strings)
|
|
483
|
+
- `numberRange` → `{ [field]: { $gte, $lte } }`
|
|
484
|
+
|
|
485
|
+
Override per field with `toCondition: (value) => unknown` (return either a primitive — wrapped in `{ [field]: ... }` — or a full clause containing `$or`/`$and`, which is merged at the top level of `where`). Useful for searching multiple paths with one input, or for translating UI values into a backend-specific shape.
|
|
486
|
+
|
|
487
|
+
```ts
|
|
488
|
+
// Search bar that matches client.name OR title OR topics:
|
|
489
|
+
{
|
|
490
|
+
id: 'q',
|
|
491
|
+
type: 'text',
|
|
492
|
+
prominent: true,
|
|
493
|
+
pinned: true,
|
|
494
|
+
toCondition: (v) => {
|
|
495
|
+
const s = String(v ?? '').trim();
|
|
496
|
+
if (!s) return undefined;
|
|
497
|
+
const like = { $regex: `.*${s}.*`, $options: 'i' };
|
|
498
|
+
return { $or: [
|
|
499
|
+
{ 'client.name': like },
|
|
500
|
+
{ title: like },
|
|
501
|
+
{ relatedTopicsText: like },
|
|
502
|
+
]};
|
|
503
|
+
},
|
|
504
|
+
}
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
> `transform` is the deprecated old name for `toCondition` and is still accepted as an alias.
|
|
508
|
+
|
|
509
|
+
### Multifilter props
|
|
510
|
+
|
|
511
|
+
| prop | type | default | notes |
|
|
512
|
+
|---|---|---|---|
|
|
513
|
+
| `id` | `string` | — | Required. |
|
|
514
|
+
| `config` | `MultifilterConfig` | — | Required. See [Field types](#field-types). |
|
|
515
|
+
| `editable` | `boolean` | `true` | When `false`, no `+` button and no X chips. |
|
|
516
|
+
| `performButton` | `boolean` | `false` | |
|
|
517
|
+
| `performLabel` | `string` | `'Buscar'` | |
|
|
518
|
+
| `performIcon` | `ReactNode` | search icon | |
|
|
519
|
+
| `performPosition` | `'inline' \| 'belowRow' \| 'externalRef'` | `'inline'` | |
|
|
520
|
+
| `performTargetRef` | `RefObject<HTMLElement>` | — | Required if `performPosition === 'externalRef'` (TODO portal). |
|
|
521
|
+
| `performOnMount` | `boolean` | `false` | Fire `onPerform` once if seeded state has values. |
|
|
522
|
+
| `onPerform` | `(snap) => void` | — | Fires when the user clicks Buscar (or `performOnMount` triggers it). |
|
|
523
|
+
| `onChange` | `(snap) => void` | — | Every change (per keystroke / option toggle). |
|
|
524
|
+
| `onStateChange` | `(snap) => void` | — | Same as `onChange`; provided for API symmetry. |
|
|
525
|
+
| `showClearAll` | `boolean` | `editable` | Clears values & active fields. |
|
|
526
|
+
| `labels` | `Partial<MultifilterLabels>` | Spanish defaults | |
|
|
527
|
+
| `className`, `persist`, `clearWhen` | as in Input/Selector | | |
|
|
528
|
+
|
|
529
|
+
---
|
|
530
|
+
|
|
531
|
+
## `EasyVisionTable`
|
|
532
|
+
|
|
533
|
+
A modular table built on TanStack React Table. Pagination and ordering modes are independent: each can be `'local'` or `'api'`. The TanStack surface is fully encapsulated — page code never imports from `@tanstack/react-table`.
|
|
534
|
+
|
|
535
|
+
### Choosing a data + filter strategy
|
|
536
|
+
|
|
537
|
+
Use this decision table to pick props before you start. Every row is a valid combination.
|
|
538
|
+
|
|
539
|
+
| Your situation | `paginationMode` / `orderingMode` | Pass | Filter UI |
|
|
540
|
+
|---|---|---|---|
|
|
541
|
+
| Full dataset already in memory, no filtering | `local` / `local` | `data={rows}` | — |
|
|
542
|
+
| Full dataset, want a built-in filter row | `local` / `local` | `data={rows}` + `multifilter` | bound multifilter |
|
|
543
|
+
| Server-paginated list with EasyVision filter chips | `api` / `api` | `fetchData` + `multifilter` | bound multifilter |
|
|
544
|
+
| Server-paginated list with **your own** search panel | `api` / `api` | `fetchData` + `externalFilter` + `refetchSignal` | external (you render it) |
|
|
545
|
+
| Hybrid: fetch once then sort/filter locally | `local` / `local` | `data={fetchedOnce}` + `multifilter` | bound multifilter |
|
|
546
|
+
| Server-paginated, sort the loaded page locally | `api` / `local` | `fetchData` + `data` (the loaded page) | either |
|
|
547
|
+
|
|
548
|
+
**Rule of thumb:** prefer the bound `multifilter` whenever its field types fit. Reach for `externalFilter`/`refetchSignal` only when you need a non-standard search UI (multi-step wizard, large form, URL-driven). Both can coexist — the multifilter's `where` overrides the external filter on key collisions.
|
|
549
|
+
|
|
550
|
+
### Minimal local example
|
|
551
|
+
|
|
552
|
+
```tsx
|
|
553
|
+
import { EasyVisionTable, defaultCell } from '@/components/easyvision';
|
|
554
|
+
|
|
555
|
+
<EasyVisionTable<User>
|
|
556
|
+
id="users"
|
|
557
|
+
data={users} // array of all rows
|
|
558
|
+
getRowId={(u) => u.id}
|
|
559
|
+
columns={[
|
|
560
|
+
{ field: 'name', header: 'Nombre' }, // auto-render
|
|
561
|
+
{ field: 'email', header: 'Email', cell: (u) => defaultCell(u.email) }, // explicit
|
|
562
|
+
]}
|
|
563
|
+
/>
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
### Minimal API example
|
|
567
|
+
|
|
568
|
+
```tsx
|
|
569
|
+
<EasyVisionTable<Alert>
|
|
570
|
+
id="alerts"
|
|
571
|
+
paginationMode="api"
|
|
572
|
+
orderingMode="api"
|
|
573
|
+
getRowId={(a) => a.id}
|
|
574
|
+
fetchData={async ({ page, itemsPerPage, sort, filter }) => {
|
|
575
|
+
const res = await api.list({
|
|
576
|
+
page, limit: itemsPerPage,
|
|
577
|
+
order: sort ? `${sort.column} ${sort.descending ? 'DESC' : 'ASC'}` : undefined,
|
|
578
|
+
where: filter?.where,
|
|
579
|
+
});
|
|
580
|
+
return { rows: res.rows, totalCount: res.total };
|
|
581
|
+
}}
|
|
582
|
+
columns={[
|
|
583
|
+
{ field: 'created', header: 'Fecha' },
|
|
584
|
+
{ field: 'client.name', header: 'Cliente' }, // nested → not sortable by default
|
|
585
|
+
{ field: 'client.sector', header: 'Sector', sortable: true }, // override per column
|
|
586
|
+
]}
|
|
587
|
+
/>
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
### Local vs API mode
|
|
591
|
+
|
|
592
|
+
| mode | what you pass | what the table does |
|
|
593
|
+
|---|---|---|
|
|
594
|
+
| `paginationMode="local"` | full `data` array | slices to current page in-memory |
|
|
595
|
+
| `paginationMode="api"` | `fetchData` callback | calls `fetchData({page, itemsPerPage, sort, filter})`; uses `result.totalCount` for the page count |
|
|
596
|
+
| `orderingMode="local"` | full `data` array | sorts in-memory by resolving the column's `field` (dot paths supported); applies a numeric-in-string heuristic so `"Plan 12"` sorts before `"Plan 100"` |
|
|
597
|
+
| `orderingMode="api"` | — | the table doesn't sort; sends `sort` to `fetchData` and renders whatever rows come back |
|
|
598
|
+
|
|
599
|
+
Mix them freely — e.g. fetch-once then sort/paginate locally, or paginate via API but sort the loaded page locally.
|
|
600
|
+
|
|
601
|
+
### Column definitions
|
|
602
|
+
|
|
603
|
+
A column is a discriminated union: a **`data`** column (default) maps to a value in the row; a **`ui`** column is purely presentational. The `type` field discriminates them.
|
|
604
|
+
|
|
605
|
+
```ts
|
|
606
|
+
// Data column — the default; you may omit `type`.
|
|
607
|
+
type DataColumn<T> = {
|
|
608
|
+
type?: 'data';
|
|
609
|
+
/** Dot-path to the value (e.g. "client.name"). Doubles as the column ID. */
|
|
610
|
+
field: string;
|
|
611
|
+
header: string | ReactNode | ((ctx) => ReactNode);
|
|
612
|
+
/** Custom renderer; receives the row item directly. Omit for the default span. */
|
|
613
|
+
cell?: (item: T) => ReactNode;
|
|
614
|
+
/** Override the default sort policy. See "Sorting defaults" below. */
|
|
615
|
+
sortable?: boolean;
|
|
616
|
+
initiallyHidden?: boolean;
|
|
617
|
+
largeScreensOnly?: boolean;
|
|
618
|
+
/** Initial column width. Number = px; string = any CSS length (e.g. '20%', '12rem'). */
|
|
619
|
+
width?: number | string;
|
|
620
|
+
/** Truncate cell content with ellipsis when it overflows the column width. */
|
|
621
|
+
truncate?: boolean;
|
|
622
|
+
/** Allow the user to drag the right edge of the header to resize this column. */
|
|
623
|
+
resizable?: boolean;
|
|
624
|
+
};
|
|
625
|
+
|
|
626
|
+
// UI column — no underlying value, never sortable.
|
|
627
|
+
type UiColumn<T> = {
|
|
628
|
+
type: 'ui';
|
|
629
|
+
field: string; // unique id
|
|
630
|
+
header: string | ReactNode | ((ctx) => ReactNode);
|
|
631
|
+
cell: (item: T) => ReactNode; // required
|
|
632
|
+
initiallyHidden?: boolean;
|
|
633
|
+
largeScreensOnly?: boolean;
|
|
634
|
+
width?: number | string;
|
|
635
|
+
truncate?: boolean;
|
|
636
|
+
resizable?: boolean;
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
export type EasyVisionColumn<T> = DataColumn<T> | UiColumn<T>;
|
|
640
|
+
```
|
|
641
|
+
|
|
642
|
+
**`field` does double duty on data columns:** it's both the column ID and the dot-path used to resolve the value. Internally the library generates an `accessorFn` that reads `row.client?.name` for `field: 'client.name'`. UI columns don't get an accessor — `field` there is just an ID.
|
|
643
|
+
|
|
644
|
+
**`cell` receives the row item directly** (no `{ row, getValue }` wrappers). For columns where you only want the resolved value with default styling, omit `cell` and the library renders it in a standard span. To get the same span styling around custom content, wrap with `defaultCell(content)`. `defaultCell` accepts an optional second argument that becomes the cell's native `title` tooltip — useful when `truncate: true` is set and you want the full text to appear on hover:
|
|
645
|
+
|
|
646
|
+
```tsx
|
|
647
|
+
import { defaultCell } from '@/components/easyvision';
|
|
648
|
+
|
|
649
|
+
{ field: 'created', header: 'Fecha', cell: (row) => defaultCell(formatDate(row.created)) }
|
|
650
|
+
|
|
651
|
+
// truncated long text — pass the full string as the second arg so it shows on hover
|
|
652
|
+
{ field: 'title', header: 'Título', truncate: true, resizable: true,
|
|
653
|
+
cell: (row) => defaultCell(row.title, row.title) }
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
#### Common patterns: do / don't
|
|
657
|
+
|
|
658
|
+
```tsx
|
|
659
|
+
// ✅ Default span — omit `cell` when the raw value is fine.
|
|
660
|
+
{ field: 'email', header: 'Email' }
|
|
661
|
+
|
|
662
|
+
// ❌ Don't reach for `cell` just to render the value.
|
|
663
|
+
{ field: 'email', header: 'Email', cell: (r) => <span>{r.email}</span> }
|
|
664
|
+
|
|
665
|
+
// ✅ Custom renderer — receive the item directly.
|
|
666
|
+
{ field: 'status', header: 'Estado', cell: (r) => <Badge>{r.status}</Badge> }
|
|
667
|
+
|
|
668
|
+
// ❌ Old TanStack-style cell context. The library does NOT pass { row, getValue }.
|
|
669
|
+
{ field: 'status', header: 'Estado', cell: ({ row }) => <Badge>{row.original.status}</Badge> }
|
|
670
|
+
|
|
671
|
+
// ✅ Pure presentational column — use `type: 'ui'` so it's structurally non-sortable
|
|
672
|
+
// and `cell` is required by the type.
|
|
673
|
+
{ type: 'ui', field: 'rowMenu', header: '', cell: (r) => <RowActions item={r} /> }
|
|
674
|
+
|
|
675
|
+
// ❌ Faking a UI column with a data column + sortable: false.
|
|
676
|
+
// Works but generates a wasted accessorFn and breaks if defaultSorting="all".
|
|
677
|
+
{ field: 'rowMenu', header: '', cell: (r) => <RowActions item={r} />, sortable: false }
|
|
678
|
+
|
|
679
|
+
// ✅ Conditional content — return null for nothing.
|
|
680
|
+
{ type: 'ui', field: 'infoIcon', header: '',
|
|
681
|
+
cell: (r) => r.info?.trim() ? <InfoIcon text={r.info} /> : null }
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
#### Sorting defaults
|
|
685
|
+
|
|
686
|
+
Resolution order, top-down:
|
|
687
|
+
|
|
688
|
+
1. `type: 'ui'` columns are never sortable.
|
|
689
|
+
2. Per-column `sortable: false` → off.
|
|
690
|
+
3. Per-column `sortable: true` → on.
|
|
691
|
+
4. Table-level `defaultSorting` prop (`'disabled' | 'nonNested' | 'all'`, default `'nonNested'`):
|
|
692
|
+
- `'disabled'` → off for every column unless explicitly opted in.
|
|
693
|
+
- `'all'` → every data column sortable, including nested fields.
|
|
694
|
+
- `'nonNested'` → flat fields sortable; nested (dot-path) fields **not** sortable in `api` mode (most APIs can't sort by nested paths). In `local` mode nested fields are sortable since the library handles dot-path comparison.
|
|
695
|
+
|
|
696
|
+
Use `sortable: true` on a single column to opt back in when your API does support sorting on it.
|
|
697
|
+
|
|
698
|
+
```tsx
|
|
699
|
+
// API supports nested sorting — opt the whole table in.
|
|
700
|
+
<EasyVisionTable defaultSorting="all" ... />
|
|
701
|
+
|
|
702
|
+
// Per-column override, regardless of table-level default.
|
|
703
|
+
{ field: 'client.sector', header: 'Sector', sortable: true }
|
|
704
|
+
```
|
|
705
|
+
|
|
706
|
+
#### Column sizing, truncation, and resizing
|
|
707
|
+
|
|
708
|
+
Three orthogonal column-level options control horizontal layout:
|
|
709
|
+
|
|
710
|
+
| option | type | effect |
|
|
711
|
+
|---|---|---|
|
|
712
|
+
| `width` | `number \| string` | Initial width. Number → px, string → any CSS length (`'20%'`, `'12rem'`, `'min(280px, 30%)'`). When omitted, the column auto-sizes to its content. |
|
|
713
|
+
| `truncate` | `boolean` | Single-line cell content; overflow becomes an ellipsis. Combine with `defaultCell(content, title)` to expose the full text as a native tooltip on hover. |
|
|
714
|
+
| `resizable` | `boolean` | Renders a drag handle on the right edge of the header. The user can drag it to resize the column live; `width` becomes the initial size. The handle has a subtle idle line that lights up on hover/drag and a 12px-wide invisible hit area for easy grabbing. |
|
|
715
|
+
|
|
716
|
+
```tsx
|
|
717
|
+
{
|
|
718
|
+
field: 'title',
|
|
719
|
+
header: 'Título',
|
|
720
|
+
width: 280,
|
|
721
|
+
truncate: true,
|
|
722
|
+
resizable: true,
|
|
723
|
+
cell: (row) => defaultCell(row.title, row.title), // full text on hover
|
|
724
|
+
}
|
|
725
|
+
```
|
|
726
|
+
|
|
727
|
+
Resizable widths are tracked by TanStack Table internally and are not persisted — they reset on reload. (If you need persistence, lift the resize state out via `tableInstance.getState().columnSizing`.)
|
|
728
|
+
|
|
729
|
+
#### Body height & sticky header
|
|
730
|
+
|
|
731
|
+
`maxBodyHeight` clamps the table body's vertical extent and makes the header `sticky top-0` while rows scroll underneath. Toolbar above and pagination footer below stay outside the scroll region, so the page itself doesn't scroll just because the dataset is long. The same wrapper handles both axes — horizontal overflow (from many or wide columns) and vertical overflow share one scroll container, so scrollbars never overlap each other.
|
|
732
|
+
|
|
733
|
+
```tsx
|
|
734
|
+
<EasyVisionTable maxBodyHeight={500} // 500px
|
|
735
|
+
<EasyVisionTable maxBodyHeight="60vh" // 60% of viewport
|
|
736
|
+
<EasyVisionTable maxBodyHeight="min(80vh, 700px)" // recommended: cap that adapts
|
|
737
|
+
<EasyVisionTable maxBodyHeight="clamp(400px, 65vh, 800px)" // floor + cap
|
|
738
|
+
```
|
|
739
|
+
|
|
740
|
+
Recommended pattern: `"min(<vh>, <px>)"`. On most monitors the px cap wins (consistent table size across resolutions); on shorter viewports the vh value kicks in so the table never overflows the visible area. When `maxBodyHeight` is omitted the table grows to its natural height and the page scrolls as before.
|
|
741
|
+
|
|
742
|
+
Both axes get a thin, theme-aware scrollbar via co-located CSS in [`EasyVisionTable.css`](./table/EasyVisionTable.css), so the styling ships with the component and works in any host project regardless of how that project handles scrollbars globally. Dark mode is detected via `prefers-color-scheme`, a `.dark` ancestor (Shadcn convention), or `[data-theme='dark']`.
|
|
743
|
+
|
|
744
|
+
### Selection
|
|
745
|
+
|
|
746
|
+
```tsx
|
|
747
|
+
<EasyVisionTable
|
|
748
|
+
enableRowSelection
|
|
749
|
+
selectAllScope="toggleable" // 'page' | 'all' | 'toggleable'
|
|
750
|
+
// getRowId defaults to (row) => String(row.id) — override only for non-standard shapes
|
|
751
|
+
onSelectionChange={(event) => {
|
|
752
|
+
// event always exposes ids[] and rows[] regardless of scope/mode.
|
|
753
|
+
pushIds(event.ids);
|
|
754
|
+
pushRows(event.rows);
|
|
755
|
+
}}
|
|
756
|
+
/>
|
|
757
|
+
```
|
|
758
|
+
|
|
759
|
+
**`SelectionChange<T>` event:**
|
|
760
|
+
|
|
761
|
+
```ts
|
|
762
|
+
type SelectionChange<T> =
|
|
763
|
+
| { scope: 'page'; ids: string[]; rows: T[] }
|
|
764
|
+
| { scope: 'all'; mode: 'in-memory'; ids: string[]; rows: T[] }
|
|
765
|
+
| { scope: 'all'; mode: 'wildcard'; ids: string[]; exceptIds: string[]; rows: T[] };
|
|
766
|
+
```
|
|
767
|
+
|
|
768
|
+
`ids` and `rows` are always present so simple consumers don't need to narrow:
|
|
769
|
+
- `page` — selected ids/rows on the current page.
|
|
770
|
+
- `all` `in-memory` (local pagination) — every row in `data`.
|
|
771
|
+
- `all` `wildcard` (api pagination) — current page rows minus `exceptIds`. The full match is server-side; pair `exceptIds` with the table's filter for backends that accept "match-all-with-exceptions" semantics (`DELETE /things?match=<filter>&except=...`).
|
|
772
|
+
|
|
773
|
+
`'toggleable'` is the default UX: a chevron next to the header checkbox lets the user switch between "select page" and "select all". When the bound multifilter performs a new search, an `'all'` selection is cleared automatically (it would otherwise be stale).
|
|
774
|
+
|
|
775
|
+
#### `selectAllResolution`: lazy vs eager wildcard
|
|
776
|
+
|
|
777
|
+
By default, "select all matching" in api mode emits a `wildcard` event (the host page is responsible for materializing the full id list when needed). Pages that need the full id list **up front** — e.g. to preview, reorder, or run in-memory transforms before submitting — can opt into eager resolution:
|
|
778
|
+
|
|
779
|
+
```tsx
|
|
780
|
+
<EasyVisionTable
|
|
781
|
+
enableRowSelection
|
|
782
|
+
selectAllResolution="eager" // 'lazy' (default) | 'eager'
|
|
783
|
+
onSelectionChange={(event) => {
|
|
784
|
+
// In eager mode, wildcard becomes mode: 'in-memory' with the full id list.
|
|
785
|
+
setSelectedIds(event.ids); // ← always complete; no resolveSelection helper needed
|
|
786
|
+
}}
|
|
787
|
+
loopback={{ ... }}
|
|
788
|
+
/>
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
What changes in `'eager'` mode (api only):
|
|
792
|
+
- The moment the user enters `'all'` scope, the table paginates `fetchData` with the active filter and captures every matching id.
|
|
793
|
+
- The selection banner shows a spinner + "Cargando…" while resolving.
|
|
794
|
+
- Once resolved, `onSelectionChange` fires with `{ scope: 'all', mode: 'in-memory', ids: [...full] }` (no `exceptIds`, no `wildcard`).
|
|
795
|
+
- **Column sorting is locked while a wildcard selection is active** — otherwise the captured id order would silently desync from the rendered view. Clearing the selection unlocks sort.
|
|
796
|
+
- The cache is invalidated on multifilter perform, on `refetchSignal` change, and when leaving `'all'` scope; the next entry re-materializes.
|
|
797
|
+
|
|
798
|
+
Trade-offs:
|
|
799
|
+
|
|
800
|
+
| Mode | Network on select-all | Reorder while selected | Untick individual rows | Best for |
|
|
801
|
+
|---|---|---|---|---|
|
|
802
|
+
| `'lazy'` (default) | none | free | via `exceptIds` | export / submit flows; no list manipulation |
|
|
803
|
+
| `'eager'` | one paginated sweep | locked | via header toggle (adds visible rows to `exceptIds`) | preview / reorder / transform before submit; one-line consumer code |
|
|
804
|
+
|
|
805
|
+
Has no effect when `paginationMode === 'local'` (the table already knows the full set).
|
|
806
|
+
|
|
807
|
+
**Selection banner.** A banner appears whenever there is *any* selection, in either scope:
|
|
808
|
+
- page-scope with N rows selected → `"N registros seleccionados"` + **Limpiar selección**
|
|
809
|
+
- all-scope → `"Todos los N registros seleccionados"` + **Limpiar selección**
|
|
810
|
+
|
|
811
|
+
Clicking *Limpiar selección* always resets to an empty page-scope selection — letting users wipe selections accumulated across pages in one click without changing modes. Override the labels via `labels.selectedCountBanner` and `labels.selectedAllBanner`.
|
|
812
|
+
|
|
813
|
+
The `'wildcard'` event in API mode is meant for backends that accept "match-all-with-exceptions" semantics — e.g. `DELETE /things?match=<filter>&except=...`.
|
|
814
|
+
|
|
815
|
+
### Highlighting rows (master/detail)
|
|
816
|
+
|
|
817
|
+
For master/detail layouts where clicking a row updates a side panel, use `isRowHighlighted` to mark the active row independently of selection:
|
|
818
|
+
|
|
819
|
+
```tsx
|
|
820
|
+
const [activeId, setActiveId] = useState<string | null>(null);
|
|
821
|
+
|
|
822
|
+
<EasyVisionTable
|
|
823
|
+
onRowClick={(row) => setActiveId(row.id)}
|
|
824
|
+
isRowHighlighted={(row) => row.id === activeId}
|
|
825
|
+
/* ... */
|
|
826
|
+
/>
|
|
827
|
+
```
|
|
828
|
+
|
|
829
|
+
Highlighted rows get a `bg-muted/50` tint plus `data-highlighted="true"` on the `<tr>` for custom styling.
|
|
830
|
+
|
|
831
|
+
### Binding a multifilter
|
|
832
|
+
|
|
833
|
+
Pass a multifilter declaration via the `multifilter` prop. It auto-mounts in the toolbar and inherits the table's namespace. Pressing Buscar resets `page = 1`, stores the snapshot, and refetches (api) or applies the where-clause client-side (local).
|
|
834
|
+
|
|
835
|
+
```tsx
|
|
836
|
+
<EasyVisionTable<Alert>
|
|
837
|
+
id="alerts"
|
|
838
|
+
paginationMode="api" orderingMode="api"
|
|
839
|
+
fetchData={fetchAlerts}
|
|
840
|
+
getRowId={(a) => a.id}
|
|
841
|
+
multifilter={{
|
|
842
|
+
id: 'mainFilter',
|
|
843
|
+
performButton: true,
|
|
844
|
+
config: {
|
|
845
|
+
fields: [
|
|
846
|
+
{ id: 'q', type: 'text', field: 'client.name', label: 'Búsqueda', prominent: true, pinned: true },
|
|
847
|
+
/* ... */
|
|
848
|
+
],
|
|
849
|
+
},
|
|
850
|
+
}}
|
|
851
|
+
columns={[/* ... */]}
|
|
852
|
+
/>
|
|
853
|
+
```
|
|
854
|
+
|
|
855
|
+
### External filter and manual refetch
|
|
856
|
+
|
|
857
|
+
When the filter UI lives **outside** the table — a custom search panel, URL query params, parent-screen state, etc. — use `externalFilter` and `refetchSignal` instead of the bound `multifilter`.
|
|
858
|
+
|
|
859
|
+
```tsx
|
|
860
|
+
const [activeFilter, setActiveFilter] = useState<{ where?: Record<string, unknown> }>({});
|
|
861
|
+
const [refetchSignal, setRefetchSignal] = useState(0);
|
|
862
|
+
|
|
863
|
+
const onSearch = () => {
|
|
864
|
+
setActiveFilter(buildWhereFromMyPanel());
|
|
865
|
+
setRefetchSignal((s) => s + 1); // forces refetch even if `where` reference is stable
|
|
866
|
+
};
|
|
867
|
+
|
|
868
|
+
<EasyVisionTable
|
|
869
|
+
paginationMode="api"
|
|
870
|
+
orderingMode="api"
|
|
871
|
+
fetchData={fetchData}
|
|
872
|
+
externalFilter={activeFilter}
|
|
873
|
+
refetchSignal={refetchSignal}
|
|
874
|
+
/* ... */
|
|
875
|
+
/>
|
|
876
|
+
```
|
|
877
|
+
|
|
878
|
+
- **`externalFilter: { where?: Record<string, unknown> }`** — merged into every `fetchData({ filter })` call. Whenever its reference changes, the table refetches.
|
|
879
|
+
- **`refetchSignal: unknown`** — changing this value forces a refetch and **resets `page` to 1** (mirroring the multifilter Buscar semantics). Useful when (a) `externalFilter` reference is stable but you want to re-query, or (b) an out-of-band event (e.g. a detail panel saving changes) should refresh the table.
|
|
880
|
+
- **Both can coexist with a bound `multifilter`.** The `where` from each is shallow-merged; **multifilter wins on key collisions**, so it can override the external filter.
|
|
881
|
+
- **Selection is not auto-cleared.** Unlike the bound multifilter (which clears `'all'`-scope selections on Buscar), the external-filter path leaves selection alone. If your UX needs it cleared on a new external search, do it explicitly:
|
|
882
|
+
```ts
|
|
883
|
+
easyVisionRegistry.getState().patch<'table'>(`${tableId}-table`, {
|
|
884
|
+
selection: { ids: {}, scope: 'page' },
|
|
885
|
+
});
|
|
886
|
+
```
|
|
887
|
+
|
|
888
|
+
### Toolbar slots
|
|
889
|
+
|
|
890
|
+
`toolbarLeft` and `toolbarRight` are arbitrary `ReactNode` slots in the table's toolbar bar (rendered above the column headers, alongside the column-visibility menu). Use them for action menus, bulk-action buttons, export controls, custom legends — anything pinned to the table chrome.
|
|
891
|
+
|
|
892
|
+
```tsx
|
|
893
|
+
<EasyVisionTable
|
|
894
|
+
toolbarLeft={<ActionManager actions={actions} />}
|
|
895
|
+
toolbarRight={<Button onClick={openSettings}>Ajustes</Button>}
|
|
896
|
+
/* ... */
|
|
897
|
+
/>
|
|
898
|
+
```
|
|
899
|
+
|
|
900
|
+
The toolbar row is hidden entirely when none of `toolbarLeft`, `toolbarRight`, or `showColumnVisibility` produce content.
|
|
901
|
+
|
|
902
|
+
### Table props
|
|
903
|
+
|
|
904
|
+
| prop | type | default |
|
|
905
|
+
|---|---|---|
|
|
906
|
+
| `id` | `string` | — required |
|
|
907
|
+
| `columns` | `EasyVisionColumn<T>[]` | — required |
|
|
908
|
+
| `paginationMode` | `'local' \| 'api'` | `'local'` |
|
|
909
|
+
| `orderingMode` | `'local' \| 'api'` | `'local'` |
|
|
910
|
+
| `defaultSorting` | `'disabled' \| 'nonNested' \| 'all'` | `'nonNested'` |
|
|
911
|
+
| `data` | `T[]` | — for local mode |
|
|
912
|
+
| `fetchData` | `(params) => Promise<{rows, totalCount}>` | — for api mode |
|
|
913
|
+
| `loopback` | `CreateLoopbackTableFetcherOptions<T>` | — declarative LoopBack shortcut; auto-builds `fetchData` and forces `paginationMode`/`orderingMode` to `'api'` (see [API adapters: LoopBack](#api-adapters-loopback)) |
|
|
914
|
+
| `onDataLoaded` | `(rows, totalCount) => void` | — fires after every successful API fetch; mirror the loaded slice into another store without wrapping `fetchData` |
|
|
915
|
+
| `multifilter` | `EasyVisionMultifilterProps` | — |
|
|
916
|
+
| `externalFilter` | `{ where?: Record<string, unknown> }` | — merged into every fetch |
|
|
917
|
+
| `localMatch` | `(row, where) => boolean` | `matchLoopbackWhere` — local-mode predicate; override or compose to extend the DSL (see [Local mode filtering](#local-mode-filtering-with-the-same-dsl--matchloopbackwhere)) |
|
|
918
|
+
| `refetchSignal` | `unknown` | — changing it refetches and resets `page` to 1 |
|
|
919
|
+
| `getRowId` | `(row) => string` | `(row) => String(row.id)` — override only for non-standard shapes |
|
|
920
|
+
| `itemsPerPage` | `number` | `10` |
|
|
921
|
+
| `itemsPerPageOptions` | `number[]` | `[10, 15, 20]` |
|
|
922
|
+
| `enableRowSelection` | `boolean` | `false` |
|
|
923
|
+
| `selectAllScope` | `'page' \| 'all' \| 'toggleable'` | `'toggleable'` |
|
|
924
|
+
| `selectAllResolution` | `'lazy' \| 'eager'` | `'lazy'` — `'eager'` materializes the full id list on wildcard select-all and locks sort while active |
|
|
925
|
+
| `onSelectionChange` | `(event) => void` | — |
|
|
926
|
+
| `isLoading` | `boolean` | `false` |
|
|
927
|
+
| `emptyMessage` | `string` | labels.noData |
|
|
928
|
+
| `emptyAction` | `ReactNode` | — |
|
|
929
|
+
| `onRowClick` | `(row) => void` | — |
|
|
930
|
+
| `isRowHighlighted` | `(row) => boolean` | — |
|
|
931
|
+
| `toolbarLeft`, `toolbarRight` | `ReactNode` | — |
|
|
932
|
+
| `showColumnVisibility` | `boolean` | `true` |
|
|
933
|
+
| `maxBodyHeight` | `number \| string` | — clamps body height (number → px, string → any CSS length); makes the header sticky and contains both-axis scroll inside the table |
|
|
934
|
+
| `labels` | `Partial<TableLabels>` | Spanish defaults |
|
|
935
|
+
| `className`, `persist` | | |
|
|
936
|
+
|
|
937
|
+
The table slice persists `page`, `itemsPerPage`, `sort`, and `selection` — set `persist={true}` to keep them across mount/unmount.
|
|
938
|
+
|
|
939
|
+
#### `TableLabels` keys
|
|
940
|
+
|
|
941
|
+
All user-visible strings on the table. Pass any subset via `labels`.
|
|
942
|
+
|
|
943
|
+
```ts
|
|
944
|
+
interface TableLabels {
|
|
945
|
+
rowsPerPage: string; // 'Resultados por página'
|
|
946
|
+
results: string; // 'Resultados'
|
|
947
|
+
page: string; // 'Página'
|
|
948
|
+
of: string; // 'de'
|
|
949
|
+
noData: string; // 'Sin resultados'
|
|
950
|
+
loading: string; // 'Cargando...'
|
|
951
|
+
customizeColumns: string; // 'Personalizar columnas'
|
|
952
|
+
selectAllPage: string; // 'Seleccionar página'
|
|
953
|
+
selectAllAll: string; // 'Seleccionar todo'
|
|
954
|
+
selectedCountBanner: (n: number) => string;// '{n} registros seleccionados'
|
|
955
|
+
selectedAllBanner: (n: number) => string; // 'Todos los {n} registros seleccionados'
|
|
956
|
+
clearSelection: string; // 'Limpiar selección'
|
|
957
|
+
}
|
|
958
|
+
```
|
|
959
|
+
|
|
960
|
+
---
|
|
961
|
+
|
|
962
|
+
## Migration cookbook
|
|
963
|
+
|
|
964
|
+
Use this when replacing an existing filter panel or table with EasyVision components. The mappings below cover the most common shapes — TanStack-based and prop-driven implementations — but the pattern generalizes.
|
|
965
|
+
|
|
966
|
+
### From a prop-driven filter panel → `EasyVisionMultifilter`
|
|
967
|
+
|
|
968
|
+
If your existing panel takes an array of filter definitions and emits a query when the user presses Search, the mapping is mechanical:
|
|
969
|
+
|
|
970
|
+
| existing concept | EasyVision equivalent |
|
|
971
|
+
|---|---|
|
|
972
|
+
| top-level component (`<FilterPanel config={...} onSearch={...} />`) | `<EasyVisionMultifilter id="..." config={...} performButton onPerform={...} />` |
|
|
973
|
+
| `config.filters[]` (array of definitions) | `config.fields[]` (same idea — see [Field types](#field-types)) |
|
|
974
|
+
| `definition.required` | `definition.mandatory` |
|
|
975
|
+
| `definition.field` (API path) | `definition.field` (same) |
|
|
976
|
+
| `definition.transform` (per-field where-builder) | `definition.toCondition` (same signature; the legacy name `transform` is still accepted as an alias) |
|
|
977
|
+
| `config.searchField` (top search bar) | `prominent: true, pinned: true` on a `type: 'text'` field in `config.fields[]` (or, for back-compat, `config.searchField` — deprecated). |
|
|
978
|
+
| `initialFilters` / `initialActiveFilters` (restored from a global store) | `persist={true}` + the slice survives mount cycles automatically |
|
|
979
|
+
| `onStateChange` (mirroring to global state) | `onStateChange` (same; or rely on the registry directly) |
|
|
980
|
+
| `onRefresh` button | n/a — pressing Buscar refetches; or call `ref.current?.perform()` |
|
|
981
|
+
|
|
982
|
+
Concepts that need new wiring:
|
|
983
|
+
|
|
984
|
+
- **Pinned vs chip vs locked.** EasyVision splits the row into a pinned-area (always visible, no `+`/X) and a chip-area (added via `+`, removed via X). Annotate each field with `pinned: true` or `locked: true` to control which area it lives in.
|
|
985
|
+
- **`editable={false}`** disables the entire add/remove UI for a fully-static layout.
|
|
986
|
+
- **Buscar dirty + mandatory gating.** The button is enabled only when every `mandatory` field has a value AND the snapshot differs from the last confirmation. There is no manual "isValid" prop to drive — the library computes it.
|
|
987
|
+
- **Nesting.** Sub-panels become a `{ type: 'multifilter', config: {...} }` field rather than a separately-mounted component.
|
|
988
|
+
|
|
989
|
+
### From a TanStack-based table → `EasyVisionTable`
|
|
990
|
+
|
|
991
|
+
Most TanStack column definitions transfer directly:
|
|
992
|
+
|
|
993
|
+
| existing | EasyVision |
|
|
994
|
+
|---|---|
|
|
995
|
+
| `ColumnDef<T>[]` with `accessorKey`, `header`, `cell` | `EasyVisionColumn<T>[]` — use `field` instead of `accessorKey` (the library auto-generates the accessor). `cell` receives the row item directly: `cell: (item) => ReactNode`. |
|
|
996
|
+
| `accessorFn: (row) => row.foo.bar` | drop — `field: 'foo.bar'` resolves dot paths automatically. |
|
|
997
|
+
| `enableSorting: false` on nested fields | drop it — automatic in `api` mode (governed by `defaultSorting`, default `'nonNested'`). Use `sortable: true` per column to opt back in, or `defaultSorting="all"` for the whole table. |
|
|
998
|
+
| `manualPagination`, `manualSorting`, `pageCount`, etc. | not needed — set `paginationMode` and `orderingMode` and the table manages it. |
|
|
999
|
+
| `getRowId` | same. Defaults to `(row) => String(row.id)`; override for rows without a top-level `id`. |
|
|
1000
|
+
| `state.sorting` + `onSortingChange` controller | gone — sort state lives in the table's slice; no controller plumbing required. |
|
|
1001
|
+
| `state.rowSelection` + `onRowSelectionChange` controller | use `onSelectionChange` for emission only; selection state is managed internally. |
|
|
1002
|
+
| Hand-rolled "select all on page" via `toggleAllPageRowsSelected` | `enableRowSelection` + `selectAllScope="page"` (default `'toggleable'` adds an "all-rows" mode). |
|
|
1003
|
+
| Hand-rolled column-visibility menu | built-in; toggle with `showColumnVisibility` (default `true`). Use `initiallyHidden: true` on a column to hide it by default. |
|
|
1004
|
+
| External `useFilteredDataTable` / pagination hook | replaced by `paginationMode="api"` + `fetchData`. Inside `fetchData` you receive `{ page, itemsPerPage, sort, filter }`. |
|
|
1005
|
+
|
|
1006
|
+
### From a hand-rolled table with local pagination/order → `EasyVisionTable`
|
|
1007
|
+
|
|
1008
|
+
| existing | EasyVision |
|
|
1009
|
+
|---|---|
|
|
1010
|
+
| `startIndex` / `itemsPerPage` slicing on a full array | `paginationMode="local"` and pass `data={fullArray}`. Slicing happens internally. |
|
|
1011
|
+
| Local sort callback + sort state | `orderingMode="local"`. The library sorts by resolving the column's `field` (dot paths supported) with a numeric-in-string heuristic. For fully custom comparators, use a `type: 'ui'` column or sort the `data` array yourself before passing it in. |
|
|
1012
|
+
| Toggling between "API mode" and "local DB mode" via a global flag | the two modes are independent props (`paginationMode` and `orderingMode`); flip one or both at the call site. |
|
|
1013
|
+
| `disableorder` per column | `sortable: false`. |
|
|
1014
|
+
| Force-enabling order on a nested column | `sortable: true` (per column) or `defaultSorting="all"` (whole table). |
|
|
1015
|
+
|
|
1016
|
+
### Common adjustments
|
|
1017
|
+
|
|
1018
|
+
- **Add `getRowId`** to every table that uses selection. Without it, TanStack uses array indices and selections appear to "jump" when the page changes.
|
|
1019
|
+
- **Drop the auth/page reset boilerplate.** Selections clear automatically when a bound multifilter performs. Page resets to 1 automatically on Buscar. Persist these via `persist={true}` if you want them kept across mount cycles.
|
|
1020
|
+
- **Inline filter values become declarative.** Instead of `useState`-driven filter state and `useEffect`-driven refetches, declare the filters in `multifilter.config.fields` and let `onPerform` drive your fetch.
|
|
1021
|
+
|
|
1022
|
+
---
|
|
1023
|
+
|
|
1024
|
+
## Integration recipes
|
|
1025
|
+
|
|
1026
|
+
### API adapters: LoopBack
|
|
1027
|
+
|
|
1028
|
+
Most backends in this project speak LoopBack (`GET /resource?filter={...}` + `GET /resource/count?filter={...}`). The library ships a first-class adapter for it: a `loopback` prop on `EasyVisionTable` (the recommended path) and a lower-level `createLoopbackTableFetcher` factory (when you need full control).
|
|
1029
|
+
|
|
1030
|
+
#### Recommended: the `loopback` prop
|
|
1031
|
+
|
|
1032
|
+
The shortest possible setup. Pass your two LoopBack endpoints declaratively; the table builds its own `fetchData`, forces `paginationMode` and `orderingMode` to `'api'`, and you never see the order/skip/where plumbing.
|
|
1033
|
+
|
|
1034
|
+
```tsx
|
|
1035
|
+
import { EasyVisionTable } from '@/components/easyvision';
|
|
1036
|
+
import { fetchAlertsByFilter, countAlertsByFilter } from '@/adapters/api/alertsApi';
|
|
1037
|
+
|
|
1038
|
+
const ALERT_FIELDS = ['id', 'created', 'scoring', /* ... */];
|
|
1039
|
+
const ALERT_INCLUDE = [{ relation: 'client' }];
|
|
1040
|
+
|
|
1041
|
+
<EasyVisionTable<Alert>
|
|
1042
|
+
id="alerts"
|
|
1043
|
+
persist
|
|
1044
|
+
columns={columns}
|
|
1045
|
+
loopback={{
|
|
1046
|
+
fetchPage: fetchAlertsByFilter, // (filter) => Promise<Alert[]>
|
|
1047
|
+
fetchCount: countAlertsByFilter, // (filter) => Promise<{ count }>
|
|
1048
|
+
include: ALERT_INCLUDE,
|
|
1049
|
+
fields: ALERT_FIELDS,
|
|
1050
|
+
defaultOrder: ['created DESC'],
|
|
1051
|
+
}}
|
|
1052
|
+
/* ... */
|
|
1053
|
+
/>
|
|
1054
|
+
```
|
|
1055
|
+
|
|
1056
|
+
The `loopback` prop is content-stable: the table compares `fetchPage`/`fetchCount` by reference and `include`/`fields`/`defaultOrder` by value, so passing an inline literal won't cause spurious refetches. No `useMemo` required at the call site.
|
|
1057
|
+
|
|
1058
|
+
The effect of providing `loopback`:
|
|
1059
|
+
|
|
1060
|
+
- `paginationMode` and `orderingMode` are forced to `'api'`.
|
|
1061
|
+
- `fetchData` is auto-generated from the options.
|
|
1062
|
+
- An explicit `fetchData` prop wins if both are present (escape hatch for custom queries on the same page).
|
|
1063
|
+
|
|
1064
|
+
#### Lower-level: `createLoopbackTableFetcher`
|
|
1065
|
+
|
|
1066
|
+
When you need to inspect, wrap, or compose the fetcher (e.g. instrument it, add logging, inject a tenant filter), use the factory directly and pass the result to `fetchData`:
|
|
1067
|
+
|
|
1068
|
+
```tsx
|
|
1069
|
+
import {
|
|
1070
|
+
EasyVisionTable,
|
|
1071
|
+
createLoopbackTableFetcher,
|
|
1072
|
+
} from '@/components/easyvision';
|
|
1073
|
+
|
|
1074
|
+
const fetchData = useMemo(
|
|
1075
|
+
() =>
|
|
1076
|
+
createLoopbackTableFetcher<Alert>({
|
|
1077
|
+
fetchPage: fetchAlertsByFilter,
|
|
1078
|
+
fetchCount: countAlertsByFilter,
|
|
1079
|
+
include: ALERT_INCLUDE,
|
|
1080
|
+
fields: ALERT_FIELDS,
|
|
1081
|
+
defaultOrder: ['created DESC'],
|
|
1082
|
+
}),
|
|
1083
|
+
[]
|
|
1084
|
+
);
|
|
1085
|
+
|
|
1086
|
+
<EasyVisionTable id="alerts" persist paginationMode="api" orderingMode="api"
|
|
1087
|
+
columns={columns} fetchData={fetchData} /* ... */ />
|
|
1088
|
+
```
|
|
1089
|
+
|
|
1090
|
+
The factory (and the `loopback` prop):
|
|
1091
|
+
- map the table's sort to LoopBack `order` (fall back to `defaultOrder` when no sort is active);
|
|
1092
|
+
- compute `skip = (page - 1) * itemsPerPage`;
|
|
1093
|
+
- forward `where` from the merged filter (multifilter ∪ external);
|
|
1094
|
+
- issue rows + count requests in parallel;
|
|
1095
|
+
- only send `where` to the count endpoint (LoopBack ignores the rest).
|
|
1096
|
+
|
|
1097
|
+
#### Importing LoopBack types
|
|
1098
|
+
|
|
1099
|
+
The adapter also exports the LoopBack `Filter` shape for hand-rolled queries (e.g. inside a custom `toCondition` on a multifilter field, or for one-off API calls):
|
|
1100
|
+
|
|
1101
|
+
```tsx
|
|
1102
|
+
import type { LoopbackFilter, LoopbackWhereValue } from '@/components/easyvision';
|
|
1103
|
+
|
|
1104
|
+
const filter: LoopbackFilter = {
|
|
1105
|
+
where: { status: { $in: ['VALIDATED', 'PENDING'] } },
|
|
1106
|
+
fields: ['id', 'status'],
|
|
1107
|
+
limit: 50,
|
|
1108
|
+
};
|
|
1109
|
+
```
|
|
1110
|
+
|
|
1111
|
+
The library makes no assumptions about how the HTTP requests are issued — `fetchPage` and `fetchCount` are plain async functions. Bring your own auth, base URL, error handling, etc.
|
|
1112
|
+
|
|
1113
|
+
For non-LoopBack backends, inline a custom `fetchData` — see [Adapting an arbitrary API response](#adapting-an-arbitrary-api-response) below — or contribute a sibling adapter (e.g. `adapters/westack.ts`) following the same pattern.
|
|
1114
|
+
|
|
1115
|
+
#### Local mode filtering with the same DSL — `matchLoopbackWhere`
|
|
1116
|
+
|
|
1117
|
+
A multifilter authored once should work the same whether it drives an API call or filters an in-memory array. The library ships `matchLoopbackWhere` — a pure evaluator for the LoopBack `where` DSL — and `EasyVisionTable` uses it as the **default** local-mode filter. No extra props are needed for the common case.
|
|
1118
|
+
|
|
1119
|
+
Supported operators: `$eq`, `$ne` / `$neq`, `$in`, `$nin`, `$gt`, `$gte`, `$lt`, `$lte`, `$regex` (with `$options`), `$exists`, plus `$and` / `$or` / `$not` and arbitrary-depth dotted paths with array fan-out.
|
|
1120
|
+
|
|
1121
|
+
##### 1. Default — the table filters internally
|
|
1122
|
+
|
|
1123
|
+
Just pass `data` and a `multifilter`. When the user clicks Buscar, the table runs `data.filter(row => matchLoopbackWhere(row, where))` before sort + pagination.
|
|
1124
|
+
|
|
1125
|
+
```tsx
|
|
1126
|
+
<EasyVisionTable<Alert>
|
|
1127
|
+
id="alerts-local"
|
|
1128
|
+
data={alerts}
|
|
1129
|
+
columns={columns}
|
|
1130
|
+
multifilter={{
|
|
1131
|
+
id: 'mainFilter',
|
|
1132
|
+
performButton: true,
|
|
1133
|
+
config: alertFilterConfig, // same config as the API path
|
|
1134
|
+
}}
|
|
1135
|
+
/>
|
|
1136
|
+
```
|
|
1137
|
+
|
|
1138
|
+
##### 2. Override (or compose) with `localMatch`
|
|
1139
|
+
|
|
1140
|
+
Need extra rules — feature flags, derived fields, hybrid logic? Pass `localMatch`. Compose with the default to keep the DSL working and add behavior on top:
|
|
1141
|
+
|
|
1142
|
+
```tsx
|
|
1143
|
+
import { EasyVisionTable, matchLoopbackWhere } from '@/components/easyvision';
|
|
1144
|
+
|
|
1145
|
+
<EasyVisionTable<Product>
|
|
1146
|
+
id="products"
|
|
1147
|
+
data={products}
|
|
1148
|
+
columns={columns}
|
|
1149
|
+
multifilter={{ id: 'productFilter', performButton: true, config }}
|
|
1150
|
+
localMatch={(row, where) =>
|
|
1151
|
+
matchLoopbackWhere(row, where) && productIsValid(row)
|
|
1152
|
+
}
|
|
1153
|
+
/>
|
|
1154
|
+
```
|
|
1155
|
+
|
|
1156
|
+
Or replace it entirely with a hand-written predicate for a non-LoopBack DSL:
|
|
1157
|
+
|
|
1158
|
+
```tsx
|
|
1159
|
+
<EasyVisionTable
|
|
1160
|
+
data={items}
|
|
1161
|
+
multifilter={multifilterProps}
|
|
1162
|
+
localMatch={(row, where) => myCustomMatcher(row, where)}
|
|
1163
|
+
/>
|
|
1164
|
+
```
|
|
1165
|
+
|
|
1166
|
+
##### 3. Standalone — use it anywhere
|
|
1167
|
+
|
|
1168
|
+
`matchLoopbackWhere` is a pure function with no React or project dependencies. Use it inside selectors, hooks, charts, export builders — anywhere you'd otherwise hand-write equivalent JS:
|
|
1169
|
+
|
|
1170
|
+
```tsx
|
|
1171
|
+
import { matchLoopbackWhere } from '@/components/easyvision';
|
|
1172
|
+
|
|
1173
|
+
// In a memoized selector:
|
|
1174
|
+
const visibleAlerts = useMemo(
|
|
1175
|
+
() => alerts.filter(a => matchLoopbackWhere(a, where)),
|
|
1176
|
+
[alerts, where]
|
|
1177
|
+
);
|
|
1178
|
+
|
|
1179
|
+
// Counting matches without rendering them:
|
|
1180
|
+
const count = rows.reduce((n, r) => n + (matchLoopbackWhere(r, where) ? 1 : 0), 0);
|
|
1181
|
+
|
|
1182
|
+
// Composing with non-DSL business rules:
|
|
1183
|
+
const eligible = banks.filter(
|
|
1184
|
+
b => matchLoopbackWhere(b, where) && hasProductType(b, '', '') > 0
|
|
1185
|
+
);
|
|
1186
|
+
```
|
|
1187
|
+
|
|
1188
|
+
Behavior on edge cases:
|
|
1189
|
+
- `undefined` or empty `where` → matches everything (no filter active).
|
|
1190
|
+
- Unknown `$operator` → `false` (fail-closed; surfaces typos early).
|
|
1191
|
+
- Plain-object equality (`{ a: { b: 1 } }`) is not supported — use dotted paths (`'a.b'`) or `$and`.
|
|
1192
|
+
|
|
1193
|
+
### Adapting an arbitrary API response
|
|
1194
|
+
|
|
1195
|
+
`fetchData` must return `{ rows: T[]; totalCount: number }`. Wrap whatever shape your backend gives you:
|
|
1196
|
+
|
|
1197
|
+
```tsx
|
|
1198
|
+
fetchData={async ({ page, itemsPerPage, sort, filter }) => {
|
|
1199
|
+
const res = await api.list({
|
|
1200
|
+
skip: (page - 1) * itemsPerPage,
|
|
1201
|
+
limit: itemsPerPage,
|
|
1202
|
+
order: sort ? `${sort.column} ${sort.descending ? 'DESC' : 'ASC'}` : undefined,
|
|
1203
|
+
where: filter?.where,
|
|
1204
|
+
});
|
|
1205
|
+
return { rows: res.data, totalCount: res.meta.totalItems };
|
|
1206
|
+
}}
|
|
1207
|
+
```
|
|
1208
|
+
|
|
1209
|
+
For a backend that returns `{ items, page, pages, total }`:
|
|
1210
|
+
|
|
1211
|
+
```tsx
|
|
1212
|
+
return { rows: res.items, totalCount: res.total };
|
|
1213
|
+
```
|
|
1214
|
+
|
|
1215
|
+
For a backend that returns no total (cursor-pagination), pass a synthetic `totalCount` and disable the page selector with a custom `labels` override or `showColumnVisibility={false}` style trimming. (True cursor support is on the deferred list.)
|
|
1216
|
+
|
|
1217
|
+
### Translating to a different filter dialect
|
|
1218
|
+
|
|
1219
|
+
The default `query.where` uses a flat `{ [field]: condition }` shape with `$regex / $in / $gte / $lte`. To emit something else (e.g. a different operator name or a wrapped `$or`/`$and` group), use **per-field `toCondition`**:
|
|
1220
|
+
|
|
1221
|
+
```ts
|
|
1222
|
+
{
|
|
1223
|
+
id: 'amount', type: 'numberRange', field: 'amount', label: 'Importe',
|
|
1224
|
+
// emit { $gte, $lte_or_whatever_your_api_uses }
|
|
1225
|
+
toCondition: (v: { min?: number; max?: number }) => ({
|
|
1226
|
+
$gte: v.min,
|
|
1227
|
+
$lte_or_whatever: v.max,
|
|
1228
|
+
}),
|
|
1229
|
+
}
|
|
1230
|
+
```
|
|
1231
|
+
|
|
1232
|
+
Or transform the whole snapshot at the call site:
|
|
1233
|
+
|
|
1234
|
+
```tsx
|
|
1235
|
+
onPerform={(snap) => {
|
|
1236
|
+
const apiWhere = mySnapshotToApiAdapter(snap);
|
|
1237
|
+
fetch('/api/items', { body: JSON.stringify({ where: apiWhere }) });
|
|
1238
|
+
}}
|
|
1239
|
+
```
|
|
1240
|
+
|
|
1241
|
+
A reusable adapter (e.g. converting EasyVision's flat `where` into a recursive `$or/$and` filter group) belongs **next to the call site or in a small `adapters/` module**, not inside the multifilter — keeps the library dialect-agnostic.
|
|
1242
|
+
|
|
1243
|
+
### Tearing down state on logout / route exit
|
|
1244
|
+
|
|
1245
|
+
Slices are cleaned up automatically when their owning component unmounts (unless `persist={true}`). To wipe everything explicitly — say on logout — use the registry directly:
|
|
1246
|
+
|
|
1247
|
+
```ts
|
|
1248
|
+
import { easyVisionRegistry } from '@/components/easyvision';
|
|
1249
|
+
|
|
1250
|
+
function logout() {
|
|
1251
|
+
await api.logout();
|
|
1252
|
+
easyVisionRegistry.getState().reset(); // drop every slice
|
|
1253
|
+
navigate('/login');
|
|
1254
|
+
}
|
|
1255
|
+
```
|
|
1256
|
+
|
|
1257
|
+
To drop a single subtree (e.g. forcing one table back to its default state):
|
|
1258
|
+
|
|
1259
|
+
```ts
|
|
1260
|
+
easyVisionRegistry.getState().drop('alerts-table'); // also drops every descendant slice
|
|
1261
|
+
```
|
|
1262
|
+
|
|
1263
|
+
### Reading state from outside React
|
|
1264
|
+
|
|
1265
|
+
Useful for export buttons, page-level "have any filters changed?" checks, etc.
|
|
1266
|
+
|
|
1267
|
+
```ts
|
|
1268
|
+
import { getSlice, easyVisionRegistry } from '@/components/easyvision';
|
|
1269
|
+
|
|
1270
|
+
// Export selected rows.
|
|
1271
|
+
const tableSlice = getSlice<'table'>('alerts-table');
|
|
1272
|
+
const selectedIds = Object.keys(tableSlice?.selection.ids ?? {});
|
|
1273
|
+
|
|
1274
|
+
// Watch for any change in the registry (rare; usually onChange/onPerform is enough).
|
|
1275
|
+
const unsub = easyVisionRegistry.subscribe((state) => {
|
|
1276
|
+
console.log(state.slices);
|
|
1277
|
+
});
|
|
1278
|
+
unsub(); // remember to unsubscribe
|
|
1279
|
+
```
|
|
1280
|
+
|
|
1281
|
+
### Persistence patterns
|
|
1282
|
+
|
|
1283
|
+
| goal | how |
|
|
1284
|
+
|---|---|
|
|
1285
|
+
| Keep filter & page across in-app navigation | `persist={true}` on the multifilter and/or table. Slices survive mount/unmount of the page that hosts them. |
|
|
1286
|
+
| Reset when the parent entity changes | `clearWhen={(snapshot) => parentId !== lastSeen.current}` |
|
|
1287
|
+
| Reset everything on logout | `easyVisionRegistry.getState().reset()` (see above) |
|
|
1288
|
+
| Reset when the URL changes | `clearWhen={() => location.pathname !== savedPath}` or call `drop(fullId)` in a route effect |
|
|
1289
|
+
| Keep across browser reloads | not built-in for v1 — wire your own `localStorage` adapter using `easyVisionRegistry.subscribe` + `getSlice` |
|
|
1290
|
+
|
|
1291
|
+
### Localizing user-visible strings
|
|
1292
|
+
|
|
1293
|
+
Every component accepts `labels?: Partial<Labels>`. The defaults are Spanish; pass any subset:
|
|
1294
|
+
|
|
1295
|
+
```tsx
|
|
1296
|
+
<EasyVisionMultifilter
|
|
1297
|
+
labels={{ perform: t('filters.search'), clear: t('common.clear') }}
|
|
1298
|
+
/* ... */
|
|
1299
|
+
/>
|
|
1300
|
+
<EasyVisionTable
|
|
1301
|
+
labels={{
|
|
1302
|
+
rowsPerPage: t('table.rowsPerPage'),
|
|
1303
|
+
of: t('common.of'),
|
|
1304
|
+
selectedAllBanner: (n) => t('table.selectedAll', { count: n }),
|
|
1305
|
+
}}
|
|
1306
|
+
/* ... */
|
|
1307
|
+
/>
|
|
1308
|
+
```
|
|
1309
|
+
|
|
1310
|
+
The library never imports a translation framework directly, so it's compatible with `react-i18next`, `react-intl`, plain dictionaries, or anything else.
|
|
1311
|
+
|
|
1312
|
+
---
|
|
1313
|
+
|
|
1314
|
+
## Gotchas
|
|
1315
|
+
|
|
1316
|
+
Things that bit us during development and are easy to miss at integration time.
|
|
1317
|
+
|
|
1318
|
+
### Layout
|
|
1319
|
+
|
|
1320
|
+
- **Tables inside a CSS grid get cut off.** CSS grid items default to `min-width: auto`, which means they expand to fit their content rather than letting the table's `overflow-auto` engage. Add `min-w-0` to each grid cell that hosts a table:
|
|
1321
|
+
|
|
1322
|
+
```tsx
|
|
1323
|
+
<div className="grid grid-cols-2 gap-4">
|
|
1324
|
+
<div className="min-w-0"><EasyVisionTable {...} /></div>
|
|
1325
|
+
<div className="min-w-0"><EasyVisionTable {...} /></div>
|
|
1326
|
+
</div>
|
|
1327
|
+
```
|
|
1328
|
+
The same fix applies to flex containers (`min-w-0` on flex children that should shrink).
|
|
1329
|
+
|
|
1330
|
+
- **Horizontal scrollbars don't appear if the host project hides scrollbars globally.** The library imports `easyvision.css` which re-enables scrollbars on its own scroll containers (`.easyvision-table-scroll`). If you also want vertical scrollbars to be visible, target the same class or add a similar override at the host level.
|
|
1331
|
+
|
|
1332
|
+
- **The selection column is `60px` wide by default** to fit checkbox + chevron in `selectAllScope="toggleable"`. If you only ever use `'page'` mode you can ignore this.
|
|
1333
|
+
|
|
1334
|
+
### Selection
|
|
1335
|
+
|
|
1336
|
+
- **`getRowId` is required when `enableRowSelection`.** Without it, TanStack uses row indices, and selections won't persist across page changes (the row at index 0 on page 2 is a different entity than the row at index 0 on page 1).
|
|
1337
|
+
- **Selection persists across pages by design.** Earlier behaviour was to clear on page change — that's a bug; the current behaviour matches what users expect.
|
|
1338
|
+
- **`'all'` scope in API mode emits `mode: 'wildcard'`.** That's because the API hasn't loaded all rows; the event tells you "select everything that matches the current filter, except these explicit ids". If your backend can't honour that contract, prefer `selectAllScope="page"`.
|
|
1339
|
+
- **Selection clears automatically only for the `'all'` scope** when the bound multifilter performs a new search (the previous "all" is stale). Page-scope selections stay; the user opted into them explicitly.
|
|
1340
|
+
|
|
1341
|
+
### Ordering
|
|
1342
|
+
|
|
1343
|
+
- **Nested-field columns are non-sortable in API mode by default.** Detection is `field.includes('.')`, controlled by the table-level `defaultSorting` prop (default `'nonNested'`). If your backend can sort by nested paths, either set `sortable: true` per column or `defaultSorting="all"` on the table. To force-disable ordering on a non-nested column, use `sortable: false`.
|
|
1344
|
+
- **`type: 'ui'` columns are never sortable** — they have no underlying value to compare. If you need a sortable derived value, use a `type: 'data'` column with a `cell` renderer instead.
|
|
1345
|
+
- **Local sort uses a numeric-in-string heuristic.** Strings like `"Plan 12"` sort by their numeric prefix. If that surprises you, sort the `data` array yourself before passing it in.
|
|
1346
|
+
|
|
1347
|
+
### Multifilter
|
|
1348
|
+
|
|
1349
|
+
- **Buscar disables itself when you "undo" your edits.** Editing a value back to the last confirmed snapshot is treated as a no-op; the dirty flag returns to `false`. Intentional — prevents the user from triggering identical refetches.
|
|
1350
|
+
- **Mandatory + nested gating is recursive.** A nested multifilter with a mandatory field that's empty disables the root Buscar button. Visible at the call site as `snapshot.isValid === false`.
|
|
1351
|
+
- **Nested multifilter `performButton: true` is local-only.** It confirms the nested snapshot (resetting that section's dirty state) but does **not** trigger the root's `onPerform`. The root multifilter still owns the "fire the API call" button.
|
|
1352
|
+
- **`searchField` is a deprecated alias.** Internally treated as a virtual prominent + pinned text field. Prefer `prominent: true, pinned: true` in `fields` for new code — same snapshot shape, same behaviour, one mental model.
|
|
1353
|
+
|
|
1354
|
+
### State
|
|
1355
|
+
|
|
1356
|
+
- **Slices are dropped on unmount unless `persist={true}`.** If you mount and unmount a component repeatedly within a single screen and want to keep state, set `persist`. If you want to drop a child's state when the parent re-mounts, leave `persist` off.
|
|
1357
|
+
- **`drop(fullId)` is prefix-based.** Dropping `userTable-table` also drops `userTable-table.mainFilter-multifilter` and every descendant. This is intentional and load-bearing for the namespace tree — but it means if you store unrelated data under a key that happens to share a prefix, it'll get nuked. Don't.
|
|
1358
|
+
- **`clearWhen` runs on every render.** Keep the predicate cheap and stable (don't allocate large objects inside it). The function receives the current snapshot; the slice is dropped and re-initialized when it returns `true`.
|
|
1359
|
+
|
|
1360
|
+
### Theming
|
|
1361
|
+
|
|
1362
|
+
- **All colours come from shadcn semantic tokens.** Components rely on `--background`, `--foreground`, `--border`, `--muted`, `--card`, `--primary`, `--destructive`, etc. If your project doesn't define these (i.e. it isn't shadcn-themed), components will render with no styling.
|
|
1363
|
+
- **`.dark` mode is automatic** if your project applies the `.dark` class on a parent. EasyVision uses no hardcoded colors.
|
|
1364
|
+
|
|
1365
|
+
---
|
|
1366
|
+
|
|
1367
|
+
## Escape hatch: direct registry access
|
|
1368
|
+
|
|
1369
|
+
The store is exported in case you need to read or mutate state outside of a component (e.g. clearing all filters on logout):
|
|
1370
|
+
|
|
1371
|
+
```ts
|
|
1372
|
+
import { easyVisionRegistry } from '@/components/easyvision';
|
|
1373
|
+
|
|
1374
|
+
// Read all slices.
|
|
1375
|
+
const slices = easyVisionRegistry.getState().slices;
|
|
1376
|
+
|
|
1377
|
+
// Drop one slice (and every descendant — prefix-based).
|
|
1378
|
+
easyVisionRegistry.getState().drop('alerts-table');
|
|
1379
|
+
|
|
1380
|
+
// Clear everything.
|
|
1381
|
+
easyVisionRegistry.getState().reset();
|
|
1382
|
+
```
|
|
1383
|
+
|
|
1384
|
+
The `getSlice<K>(fullId)` helper returns a typed slice for direct reads:
|
|
1385
|
+
|
|
1386
|
+
```ts
|
|
1387
|
+
import { getSlice } from '@/components/easyvision';
|
|
1388
|
+
|
|
1389
|
+
const tableSlice = getSlice<'table'>('alerts-table');
|
|
1390
|
+
console.log(tableSlice?.page, tableSlice?.sort);
|
|
1391
|
+
```
|