@easyvision/easyvision-ui 1.8.0 → 1.9.0

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 CHANGED
@@ -43,6 +43,9 @@ import {
43
43
  - [Binding a multifilter](#binding-a-multifilter)
44
44
  - [External filter and manual refetch](#external-filter-and-manual-refetch)
45
45
  - [Toolbar slots](#toolbar-slots)
46
+ - [`EasyVisionExportButton`](#easyvisionexportbutton)
47
+ - [What gets exported](#what-gets-exported)
48
+ - [Resolving table ids](#resolving-table-ids)
46
49
  - [Migration cookbook](#migration-cookbook)
47
50
  - [Integration recipes](#integration-recipes)
48
51
  - [API adapters: LoopBack](#api-adapters-loopback)
@@ -796,6 +799,14 @@ type DataColumn<T> = {
796
799
  truncate?: boolean;
797
800
  /** Allow the user to drag the right edge of the header to resize this column. */
798
801
  resizable?: boolean;
802
+ /** Header text in an exported sheet. Defaults to `header` when it's a plain string, else `field`. */
803
+ exportHeader?: string;
804
+ /** Cell value in an exported sheet. Defaults to the value at `field` (arrays joined by ", "). */
805
+ exportValue?: (item: T) => ExportCellValue;
806
+ /** Per-cell styling in an exported sheet. Return `undefined` to leave a cell unstyled. */
807
+ exportStyle?: (value: ExportCellValue, item: T) => ExportCellStyle | undefined;
808
+ /** Include this column in exports. Default: `true` for `data` columns, `false` for `ui` columns. */
809
+ exportable?: boolean;
799
810
  };
800
811
 
801
812
  // UI column — no underlying value, never sortable.
@@ -809,11 +820,34 @@ type UiColumn<T> = {
809
820
  width?: number | string;
810
821
  truncate?: boolean;
811
822
  resizable?: boolean;
823
+ /** See data-column docs. */
824
+ exportHeader?: string;
825
+ /** See data-column docs. A `ui` column has no underlying value, so this is the only way to give it one. */
826
+ exportValue?: (item: T) => ExportCellValue;
827
+ /** See data-column docs. */
828
+ exportStyle?: (value: ExportCellValue, item: T) => ExportCellStyle | undefined;
829
+ /** `ui` columns default to `false` here — opt in alongside `exportValue` to export a computed column. */
830
+ exportable?: boolean;
812
831
  };
813
832
 
814
833
  export type EasyVisionColumn<T> = DataColumn<T> | UiColumn<T>;
815
834
  ```
816
835
 
836
+ `exportHeader` / `exportValue` / `exportStyle` / `exportable` only affect [`EasyVisionExportButton`](#easyvisionexportbutton) — they have no effect on what's rendered on screen. A worked `exportStyle` example, colouring a score cell by band:
837
+
838
+ ```ts
839
+ {
840
+ field: 'score',
841
+ header: 'Score',
842
+ exportStyle: (value) =>
843
+ typeof value === 'number' && value >= 3.5
844
+ ? { fill: 'FF991B1B', fontColor: 'FFFFFFFF', bold: true } // dark red, white bold text
845
+ : typeof value === 'number' && value >= 2
846
+ ? { fill: 'FFF59E0B', fontColor: 'FF1F2937' } // amber
847
+ : undefined, // leave low scores unstyled
848
+ }
849
+ ```
850
+
817
851
  **`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.
818
852
 
819
853
  **`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:
@@ -1216,6 +1250,61 @@ interface TableLabels {
1216
1250
 
1217
1251
  ---
1218
1252
 
1253
+ ## `EasyVisionExportButton`
1254
+
1255
+ Writes one or more registered tables into a single `.xlsx` file, one worksheet per table. It doesn't hold any data itself — every mounted `EasyVisionTable` registers an **export source** (a pair of resolvers: columns and rows) keyed by its `fullId`, and the button just looks those up by the ids you pass in `tables`.
1256
+
1257
+ ### Minimal usage
1258
+
1259
+ ```tsx
1260
+ <EasyVisionExportButton
1261
+ tables={['localTable', 'apiTable']}
1262
+ sheetNames={{ localTable: 'Local', apiTable: 'API' }}
1263
+ filename="risk-evaluations"
1264
+ />
1265
+ ```
1266
+
1267
+ Clicking it resolves `localTable` and `apiTable` against the tables mounted nearby, pulls each one's current rows and visible columns, and downloads `risk-evaluations_<ISO timestamp>.xlsx` with two sheets named `Local` and `API`. A table id with no `sheetNames` override falls back to the table's own `id` as the sheet name.
1268
+
1269
+ ### Props
1270
+
1271
+ | prop | type | default | notes |
1272
+ |---|---|---|---|
1273
+ | `tables` | `string[]` | — required | Table ids, in sheet order. See [Resolving table ids](#resolving-table-ids) below. |
1274
+ | `filename` | `string` | — required | Base name. An ISO timestamp and `.xlsx` are appended. |
1275
+ | `sheetNames` | `Record<string, string>` | — | Per-table sheet-name override, keyed by the same id passed in `tables`. Sheet names are sanitized (invalid Excel characters replaced with `-`, truncated to 31 chars) and de-duplicated automatically. |
1276
+ | `labels` | `Partial<ExportLabels>` | Spanish defaults | `{ export, exporting }` — button text for idle and in-flight states. |
1277
+ | `onError` | `(error: unknown) => void` | — | A fetch or workbook-building failure aborts the whole export — no partial file is written. Also fires when *some but not all* ids in `tables` fail to resolve, with an `Error` naming the unresolved ids — this catches a typo'd or unmounted table id before it can silently drop a sheet from an otherwise-successful export. |
1278
+ | `onEmpty` | `() => void` | — | Fires when nothing was written: **no** id in `tables` resolved to a mounted table (every id failed together, e.g. the button rendered before any table mounted), or every sheet that did resolve had zero visible columns or zero matching rows. A *partial* resolution failure — some ids resolved, some didn't — is reported via `onError` instead, not `onEmpty`, so it isn't mistaken for "nothing to export". The button does **not** disable itself when a table id fails to resolve or a table has nothing to export — it always attempts the export and reports the outcome via `onEmpty` / `onError`, since a source can legitimately empty out between renders (a hidden column, a narrowed multifilter, an unmounted table). |
1279
+ | `disabled` | `boolean` | `false` | External disable, e.g. while a parent form is invalid. |
1280
+ | `className` | `string` | — | |
1281
+ | `icon` | `ReactNode` | a download icon | Replaces the default idle-state icon. The spinner shown while exporting is not overridable. |
1282
+
1283
+ ### What gets exported
1284
+
1285
+ **Rows** are the ticked selection when there is one — page-scope ids, or an all-scope selection minus any `exceptIds` — and otherwise every row matching the table's current multifilter plus `externalFilter`. To assemble "every row" in API mode, the export first pages through `fetchData` under the hood to collect the complete matching set (the same helper `selectAllResolution="eager"` uses internally), then applies the selection filter to it — so an export is never limited to whatever page happens to be on screen, and behaves the same regardless of the table's `selectAllResolution` setting. Local mode already holds the filtered set in memory, so no extra fetching happens there.
1286
+
1287
+ **Columns** are the table's currently visible, exportable columns, in declared order. Concretely:
1288
+ - A column must pass `isVisible` — the same visibility state `ColumnVisibilityMenu` (the **Columnas** button in the table toolbar) toggles. Hide a column there and it's gone from the sheet; show it and it reappears. This makes `ColumnVisibilityMenu` double as export column customization — there is no separate export-column picker.
1289
+ - A column must be exportable: `data` columns are exportable by default, `ui` columns are not (a `ui` column has no underlying value — opt it in with `exportable: true` plus an `exportValue` to export something computed).
1290
+ - **`largeScreensOnly` columns always export**, even when the viewport is too narrow to render them. `largeScreensOnly` is a CSS-only responsive hint — it never enters the visibility state — so if it affected the export, the same click would produce a different file on a phone than on a wide monitor. Hide a column from exports on purpose with `exportable: false` instead.
1291
+
1292
+ Both resolvers run at export-click time, not at table-mount time, so a column toggle, a fresh multifilter query, or a changed selection made a second before clicking is always reflected — nothing needs to be re-registered.
1293
+
1294
+ ### Resolving table ids
1295
+
1296
+ The button must render **inside the same namespace as the tables it names**. An id in `tables` is qualified through the surrounding namespace first, the same way a nested multifilter field is (see [The `id` rule](#the-id-rule)): `'localTable'` becomes `localTable-table` when the button sits at the top level (no enclosing namespace), or `parentId.localTable-table` when it's nested under something with `id="parentId"`.
1297
+
1298
+ Rendering the button as a plain sibling of the tables — as in the demo — is the simple case: both the tables and the button see the same (usually empty) surrounding namespace, so local ids just work.
1299
+
1300
+ Rendering it **inside a table's own `toolbarLeft` / `toolbarRight`** (a natural spot per [Toolbar slots](#toolbar-slots)) is different: that slot renders inside *that table's* namespace, so a local id would be qualified as `<hostTableId>-table.<name>-table` — which never matches, even for the table hosting the button itself. In that placement, pass the target table's **fully-qualified id** instead (its own `id` with `-table` appended, e.g. `'orders-table'`).
1301
+
1302
+ Resolution is always **namespace-first**: the id is qualified through the surrounding namespace and looked up under that name first; only if that lookup misses is the raw id tried verbatim as a fallback. A fully-qualified id (one already ending in `-table`) doesn't *bypass* namespace resolution — the namespaced probe still runs first and would win if it happened to match — it just normally misses (a genuine local id doesn't already carry a `-table` suffix), so the fallback is what actually resolves it. This fallback is the escape hatch for exporting a table the button can't reach by local-id lookup, including the table it's nested inside.
1303
+
1304
+ If the target table is itself nested under another namespaced component, its fully-qualified id is the **full chain**, not just its own `id` with `-table` appended: a table declared with `id="orders"` inside something with `id="page"` registers as `page-table.orders-table`, so that's the string to pass — `'orders-table'` alone won't match it.
1305
+
1306
+ ---
1307
+
1219
1308
  ## Migration cookbook
1220
1309
 
1221
1310
  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.
@@ -392,3 +392,10 @@
392
392
  .ev-cv-item {
393
393
  text-transform: capitalize;
394
394
  }
395
+
396
+ /* ---------- Export button ---------- */
397
+ .ev-export-icon {
398
+ margin-right: 0.5rem;
399
+ height: 1rem;
400
+ width: 1rem;
401
+ }
package/dist/index.cjs CHANGED
@@ -20,6 +20,9 @@ var locale = require('date-fns/locale');
20
20
  var reactDayPicker = require('react-day-picker');
21
21
  var reactTable = require('@tanstack/react-table');
22
22
  var DropdownMenuPrimitive = require('@radix-ui/react-dropdown-menu');
23
+ var ExcelJS = require('exceljs');
24
+
25
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
23
26
 
24
27
  function _interopNamespace(e) {
25
28
  if (e && e.__esModule) return e;
@@ -44,6 +47,7 @@ var SelectPrimitive__namespace = /*#__PURE__*/_interopNamespace(SelectPrimitive)
44
47
  var PopoverPrimitive__namespace = /*#__PURE__*/_interopNamespace(PopoverPrimitive);
45
48
  var CheckboxPrimitive__namespace = /*#__PURE__*/_interopNamespace(CheckboxPrimitive);
46
49
  var DropdownMenuPrimitive__namespace = /*#__PURE__*/_interopNamespace(DropdownMenuPrimitive);
50
+ var ExcelJS__default = /*#__PURE__*/_interopDefault(ExcelJS);
47
51
 
48
52
  // index.ts
49
53
  function cn(...inputs) {
@@ -1863,6 +1867,16 @@ function compareByPath(a, b, path, descending) {
1863
1867
  return descending ? bs.localeCompare(as) : as.localeCompare(bs);
1864
1868
  }
1865
1869
 
1870
+ // table/sortLocalRows.ts
1871
+ function sortLocalRows(rows, columns, sort) {
1872
+ if (!sort) return rows;
1873
+ const col = columns.find((c) => c.field === sort.column);
1874
+ if (!col || col.type === "ui") return rows;
1875
+ const next = [...rows];
1876
+ next.sort((a, b) => compareByPath(a, b, col.field, sort.descending));
1877
+ return next;
1878
+ }
1879
+
1866
1880
  // table/useTableData.ts
1867
1881
  function useTableData({
1868
1882
  data,
@@ -1876,12 +1890,7 @@ function useTableData({
1876
1890
  return React9.useMemo(() => {
1877
1891
  let rows = data ?? [];
1878
1892
  if (orderingMode === "local" && sort) {
1879
- const col = columns.find((c) => c.field === sort.column);
1880
- if (col && col.type !== "ui") {
1881
- const next = [...rows];
1882
- next.sort((a, b) => compareByPath(a, b, col.field, sort.descending));
1883
- rows = next;
1884
- }
1893
+ rows = sortLocalRows(rows, columns, sort);
1885
1894
  }
1886
1895
  const totalCount = rows.length;
1887
1896
  if (paginationMode === "local") {
@@ -1891,6 +1900,63 @@ function useTableData({
1891
1900
  return { rows, totalCount };
1892
1901
  }, [data, columns, page, itemsPerPage, sort, paginationMode, orderingMode]);
1893
1902
  }
1903
+
1904
+ // table/applySelection.ts
1905
+ function applySelection(rows, selection, getRowId) {
1906
+ if (selection.scope === "all") {
1907
+ const except = selection.exceptIds;
1908
+ if (!except || Object.keys(except).length === 0) return rows;
1909
+ return rows.filter((row) => !except[getRowId(row)]);
1910
+ }
1911
+ const ids = selection.ids;
1912
+ if (!ids || Object.keys(ids).length === 0) return rows;
1913
+ return rows.filter((row) => ids[getRowId(row)]);
1914
+ }
1915
+
1916
+ // table/columnVisibility.ts
1917
+ function resolveColumnVisibility(columns, sliceVisibility) {
1918
+ const defaults = {};
1919
+ for (const column of columns) {
1920
+ if (column.initiallyHidden) defaults[column.field] = false;
1921
+ }
1922
+ return { ...defaults, ...sliceVisibility };
1923
+ }
1924
+ var isColumnVisible = (visibility, field) => visibility[field] !== false;
1925
+
1926
+ // table/fetchAllRows.ts
1927
+ var FETCH_ALL_PAGE_SIZE = 200;
1928
+ var mergeFilters = (externalFilter, multifilterQuery) => externalFilter || multifilterQuery ? {
1929
+ ...multifilterQuery,
1930
+ where: {
1931
+ ...externalFilter?.where ?? {},
1932
+ ...multifilterQuery?.where ?? {}
1933
+ }
1934
+ } : void 0;
1935
+ async function fetchAllRows({
1936
+ fetchData,
1937
+ filter,
1938
+ sort,
1939
+ idsOnly = false,
1940
+ pageSize = FETCH_ALL_PAGE_SIZE,
1941
+ shouldContinue
1942
+ }) {
1943
+ const collected = [];
1944
+ let knownTotal = Infinity;
1945
+ for (let page = 1; collected.length < knownTotal; page++) {
1946
+ const result = await fetchData({
1947
+ page,
1948
+ itemsPerPage: pageSize,
1949
+ sort,
1950
+ filter,
1951
+ idsOnly
1952
+ });
1953
+ if (shouldContinue && !shouldContinue()) return null;
1954
+ knownTotal = result.totalCount;
1955
+ collected.push(...result.rows);
1956
+ if (result.rows.length < pageSize) break;
1957
+ }
1958
+ return collected;
1959
+ }
1894
1960
  var DropdownMenu = DropdownMenuPrimitive__namespace.Root;
1895
1961
  var DropdownMenuTrigger = DropdownMenuPrimitive__namespace.Trigger;
1896
1962
  var DropdownMenuRadioGroup = DropdownMenuPrimitive__namespace.RadioGroup;
@@ -2282,6 +2348,48 @@ function matchLeaf(value, condition) {
2282
2348
  }
2283
2349
  return true;
2284
2350
  }
2351
+
2352
+ // export/sources.ts
2353
+ var sources = /* @__PURE__ */ new Map();
2354
+ var registerExportSource = (fullId, source) => {
2355
+ sources.set(fullId, source);
2356
+ };
2357
+ var unregisterExportSource = (fullId) => {
2358
+ sources.delete(fullId);
2359
+ };
2360
+ var getExportSource = (fullId) => sources.get(fullId);
2361
+ var resolveExportSource = (parentFullId, tableId) => getExportSource(childFullIdOf(parentFullId, tableId, "table")) ?? getExportSource(tableId);
2362
+
2363
+ // export/exportColumns.ts
2364
+ var toExportCellValue = (raw) => {
2365
+ if (raw == null) return null;
2366
+ if (Array.isArray(raw)) return raw.join(", ");
2367
+ if (raw instanceof Date) return raw;
2368
+ const kind = typeof raw;
2369
+ if (kind === "string" || kind === "number" || kind === "boolean") {
2370
+ return raw;
2371
+ }
2372
+ return String(raw);
2373
+ };
2374
+ var isExportable = (column) => column.exportable ?? column.type !== "ui";
2375
+ var exportHeaderOf = (column) => column.exportHeader ?? (typeof column.header === "string" ? column.header : column.field);
2376
+ function toExportColumns(columns, isVisible) {
2377
+ return columns.filter((column) => isExportable(column) && isVisible(column.field)).map((column) => {
2378
+ const exportValue = column.exportValue;
2379
+ const exportStyle = column.exportStyle;
2380
+ const field = column.field;
2381
+ const isUi = column.type === "ui";
2382
+ return {
2383
+ header: exportHeaderOf(column),
2384
+ getValue: (item) => {
2385
+ if (exportValue) return toExportCellValue(exportValue(item));
2386
+ if (isUi) return null;
2387
+ return toExportCellValue(getByPath(item, field));
2388
+ },
2389
+ getStyle: exportStyle ? (value, item) => exportStyle(value, item) : void 0
2390
+ };
2391
+ });
2392
+ }
2285
2393
  var DEFAULT_LABELS2 = {
2286
2394
  rowsPerPage: "Resultados por p\xE1gina:",
2287
2395
  results: "Resultados",
@@ -2398,14 +2506,7 @@ function EasyVisionTable(props) {
2398
2506
  const seq = ++fetchSeqRef.current;
2399
2507
  setApiLoading(true);
2400
2508
  try {
2401
- const mfQuery = lastSnapshotRef.current?.query;
2402
- const merged = externalFilter || mfQuery ? {
2403
- ...mfQuery,
2404
- where: {
2405
- ...externalFilter?.where ?? {},
2406
- ...mfQuery?.where ?? {}
2407
- }
2408
- } : void 0;
2509
+ const merged = mergeFilters(externalFilter, lastSnapshotRef.current?.query);
2409
2510
  const result = await fetchData({
2410
2511
  page,
2411
2512
  itemsPerPage,
@@ -2429,38 +2530,23 @@ function EasyVisionTable(props) {
2429
2530
  const seq = ++eagerSeqRef.current;
2430
2531
  setIsResolvingEager(true);
2431
2532
  try {
2432
- const mfQuery = lastSnapshotRef.current?.query;
2433
- const merged = externalFilter || mfQuery ? {
2434
- ...mfQuery,
2435
- where: {
2436
- ...externalFilter?.where ?? {},
2437
- ...mfQuery?.where ?? {}
2438
- }
2439
- } : void 0;
2440
- const PAGE_SIZE = 200;
2533
+ const fetched = await fetchAllRows({
2534
+ fetchData,
2535
+ filter: mergeFilters(externalFilter, lastSnapshotRef.current?.query),
2536
+ sort,
2537
+ idsOnly: !collectRows,
2538
+ shouldContinue: () => seq === eagerSeqRef.current
2539
+ });
2540
+ if (fetched === null || seq !== eagerSeqRef.current) return;
2441
2541
  const ids = [];
2442
2542
  const rowsAcc = [];
2443
- let knownTotal = Infinity;
2444
- for (let p = 1; ids.length < knownTotal; p++) {
2445
- const result = await fetchData({
2446
- page: p,
2447
- itemsPerPage: PAGE_SIZE,
2448
- sort,
2449
- filter: merged,
2450
- idsOnly: !collectRows
2451
- });
2452
- if (seq !== eagerSeqRef.current) return;
2453
- knownTotal = result.totalCount;
2454
- for (const row of result.rows) {
2455
- const rid = getRowId(row);
2456
- if (rid) {
2457
- ids.push(rid);
2458
- if (collectRows) rowsAcc.push(row);
2459
- }
2543
+ for (const row of fetched) {
2544
+ const rid = getRowId(row);
2545
+ if (rid) {
2546
+ ids.push(rid);
2547
+ if (collectRows) rowsAcc.push(row);
2460
2548
  }
2461
- if (result.rows.length < PAGE_SIZE) break;
2462
2549
  }
2463
- if (seq !== eagerSeqRef.current) return;
2464
2550
  setEagerAllIds(ids);
2465
2551
  if (collectRows) setEagerAllRows(rowsAcc);
2466
2552
  } finally {
@@ -2525,17 +2611,62 @@ function EasyVisionTable(props) {
2525
2611
  };
2526
2612
  return [checkboxCol, ...tanstackColumns];
2527
2613
  }, [enableRowSelection, tanstackColumns]);
2528
- const visibilityDefaults = React9.useMemo(() => {
2529
- const v = {};
2530
- for (const c of columns) {
2531
- if (c.initiallyHidden) v[c.field] = false;
2532
- }
2533
- return v;
2534
- }, [columns]);
2535
2614
  const columnVisibility = React9.useMemo(
2536
- () => ({ ...visibilityDefaults, ...slice.columnVisibility }),
2537
- [visibilityDefaults, slice.columnVisibility]
2615
+ () => resolveColumnVisibility(columns, slice.columnVisibility),
2616
+ [columns, slice.columnVisibility]
2538
2617
  );
2618
+ const exportStateRef = React9.useRef({
2619
+ columns,
2620
+ columnVisibility,
2621
+ selection,
2622
+ fetchData,
2623
+ externalFilter,
2624
+ sort,
2625
+ filteredData,
2626
+ isApi,
2627
+ getRowId
2628
+ });
2629
+ exportStateRef.current = {
2630
+ columns,
2631
+ columnVisibility,
2632
+ selection,
2633
+ fetchData,
2634
+ externalFilter,
2635
+ sort,
2636
+ filteredData,
2637
+ isApi,
2638
+ getRowId
2639
+ };
2640
+ React9.useEffect(() => {
2641
+ registerExportSource(fullId, {
2642
+ sheetName: id,
2643
+ getColumns: () => {
2644
+ const state = exportStateRef.current;
2645
+ return toExportColumns(
2646
+ state.columns,
2647
+ (field) => isColumnVisible(state.columnVisibility, field)
2648
+ );
2649
+ },
2650
+ getRows: async () => {
2651
+ const state = exportStateRef.current;
2652
+ let all;
2653
+ if (state.isApi && state.fetchData) {
2654
+ all = await fetchAllRows({
2655
+ fetchData: state.fetchData,
2656
+ filter: mergeFilters(
2657
+ state.externalFilter,
2658
+ lastSnapshotRef.current?.query
2659
+ ),
2660
+ sort: state.sort
2661
+ }) ?? [];
2662
+ } else {
2663
+ all = sortLocalRows(state.filteredData ?? [], state.columns, state.sort);
2664
+ }
2665
+ return applySelection(all, state.selection, state.getRowId);
2666
+ }
2667
+ });
2668
+ return () => unregisterExportSource(fullId);
2669
+ }, [fullId, id]);
2539
2670
  const resizableFields = React9.useMemo(() => {
2540
2671
  const s = /* @__PURE__ */ new Set();
2541
2672
  for (const c of columns) if (c.resizable) s.add(c.field);
@@ -2590,6 +2721,14 @@ function EasyVisionTable(props) {
2590
2721
  getCoreRowModel: reactTable.getCoreRowModel(),
2591
2722
  manualPagination: true,
2592
2723
  manualSorting: true,
2724
+ // TanStack picks the first sort direction per column by sniffing row 0 of
2725
+ // the *current* page (`getAutoSortDir`: string → asc, anything else → desc).
2726
+ // With server-side data that row changes between clicks, so the asc/desc/off
2727
+ // cycle collapses — e.g. a nullable date column whose page-1 ASC result leads
2728
+ // with a null row flips firstSortDir to 'desc' and the next click removes the
2729
+ // sort instead of going descending. Pin it so the cycle is always off → asc
2730
+ // → desc → off, on every page.
2731
+ sortDescFirst: false,
2593
2732
  enableColumnResizing: true,
2594
2733
  columnResizeMode: "onChange",
2595
2734
  pageCount: Math.ceil(totalCount / itemsPerPage),
@@ -2995,6 +3134,171 @@ function EasyVisionTable(props) {
2995
3134
  ] })
2996
3135
  ] }) });
2997
3136
  }
3137
+ var HEADER_FILL_ARGB = "FFCCCCCC";
3138
+ var MIN_COLUMN_WIDTH = 10;
3139
+ var COLUMN_WIDTH_PADDING = 2;
3140
+ var XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
3141
+ var INVALID_SHEET_CHARS = /[*?:\\/[\]]/g;
3142
+ var MAX_SHEET_NAME = 31;
3143
+ var FALLBACK_SHEET_NAME = "Hoja";
3144
+ var sanitizeSheetName = (name) => name.replace(INVALID_SHEET_CHARS, "-").substring(0, MAX_SHEET_NAME) || FALLBACK_SHEET_NAME;
3145
+ var uniqueSheetName = (raw, taken) => {
3146
+ const base = sanitizeSheetName(raw);
3147
+ if (!taken.has(base)) {
3148
+ taken.add(base);
3149
+ return base;
3150
+ }
3151
+ for (let n = 2; ; n++) {
3152
+ const suffix = `_${n}`;
3153
+ const candidate = base.substring(0, MAX_SHEET_NAME - suffix.length) + suffix;
3154
+ if (!taken.has(candidate)) {
3155
+ taken.add(candidate);
3156
+ return candidate;
3157
+ }
3158
+ }
3159
+ };
3160
+ var downloadBlob = (blob, filename) => {
3161
+ const url = URL.createObjectURL(blob);
3162
+ const anchor = document.createElement("a");
3163
+ anchor.href = url;
3164
+ anchor.download = filename;
3165
+ document.body.appendChild(anchor);
3166
+ anchor.click();
3167
+ anchor.remove();
3168
+ setTimeout(() => URL.revokeObjectURL(url), 0);
3169
+ };
3170
+ var autoFitColumns = (worksheet) => {
3171
+ worksheet.columns.forEach((column) => {
3172
+ let longest = 0;
3173
+ column.eachCell?.({ includeEmpty: false }, (cell) => {
3174
+ const length = cell.value instanceof Date ? cell.value.toISOString().length : cell.text.length;
3175
+ if (length > longest) longest = length;
3176
+ });
3177
+ column.width = Math.max(MIN_COLUMN_WIDTH, longest + COLUMN_WIDTH_PADDING);
3178
+ });
3179
+ };
3180
+ async function buildWorkbook(sheets) {
3181
+ const usable = sheets.filter(
3182
+ (sheet) => sheet.rows.length > 0 && sheet.columns.length > 0
3183
+ );
3184
+ if (usable.length === 0) return null;
3185
+ const workbook = new ExcelJS__default.default.Workbook();
3186
+ const takenNames = /* @__PURE__ */ new Set();
3187
+ for (const sheet of usable) {
3188
+ const worksheet = workbook.addWorksheet(uniqueSheetName(sheet.name, takenNames));
3189
+ const headerRow = worksheet.addRow(sheet.columns.map((c) => c.header));
3190
+ headerRow.eachCell((cell) => {
3191
+ cell.fill = {
3192
+ type: "pattern",
3193
+ pattern: "solid",
3194
+ fgColor: { argb: HEADER_FILL_ARGB }
3195
+ };
3196
+ cell.font = { bold: true };
3197
+ });
3198
+ for (const item of sheet.rows) {
3199
+ const values = sheet.columns.map((column) => column.getValue(item));
3200
+ const row = worksheet.addRow(values);
3201
+ sheet.columns.forEach((column, index) => {
3202
+ const style = column.getStyle?.(values[index], item);
3203
+ if (!style) return;
3204
+ const cell = row.getCell(index + 1);
3205
+ if (style.fill) {
3206
+ cell.fill = {
3207
+ type: "pattern",
3208
+ pattern: "solid",
3209
+ fgColor: { argb: style.fill }
3210
+ };
3211
+ }
3212
+ if (style.fontColor || style.bold) {
3213
+ cell.font = {
3214
+ bold: !!style.bold,
3215
+ ...style.fontColor ? { color: { argb: style.fontColor } } : {}
3216
+ };
3217
+ }
3218
+ });
3219
+ }
3220
+ autoFitColumns(worksheet);
3221
+ }
3222
+ return workbook;
3223
+ }
3224
+ async function exportSheets(sheets, options) {
3225
+ const workbook = await buildWorkbook(sheets);
3226
+ if (!workbook) return false;
3227
+ const buffer = await workbook.xlsx.writeBuffer();
3228
+ const blob = new Blob([buffer], { type: XLSX_MIME });
3229
+ const filename = `${options.filename}_${(/* @__PURE__ */ new Date()).toISOString()}.xlsx`;
3230
+ (options.download ?? downloadBlob)(blob, filename);
3231
+ return true;
3232
+ }
3233
+ var DEFAULT_LABELS3 = {
3234
+ export: "Exportar",
3235
+ exporting: "Exportando..."
3236
+ };
3237
+ function EasyVisionExportButton({
3238
+ tables,
3239
+ filename,
3240
+ sheetNames,
3241
+ labels: labelOverrides,
3242
+ onError,
3243
+ onEmpty,
3244
+ disabled = false,
3245
+ className,
3246
+ icon
3247
+ }) {
3248
+ const labels = { ...DEFAULT_LABELS3, ...labelOverrides };
3249
+ const parentFullId = useParentFullId();
3250
+ const [isExporting, setIsExporting] = React9.useState(false);
3251
+ const handleClick = React9.useCallback(async () => {
3252
+ setIsExporting(true);
3253
+ try {
3254
+ const resolved = tables.map((tableId) => ({
3255
+ tableId,
3256
+ source: resolveExportSource(parentFullId, tableId)
3257
+ }));
3258
+ const unresolved = resolved.filter((r) => !r.source).map((r) => r.tableId);
3259
+ if (unresolved.length > 0 && unresolved.length < tables.length) {
3260
+ onError?.(
3261
+ new Error(
3262
+ `EasyVisionExportButton: could not resolve table id(s): ${unresolved.join(", ")}`
3263
+ )
3264
+ );
3265
+ return;
3266
+ }
3267
+ const sheets = [];
3268
+ for (const { tableId, source } of resolved) {
3269
+ if (!source) continue;
3270
+ const columns = source.getColumns();
3271
+ if (columns.length === 0) continue;
3272
+ sheets.push({
3273
+ name: sheetNames?.[tableId] ?? source.sheetName,
3274
+ columns,
3275
+ rows: await source.getRows()
3276
+ });
3277
+ }
3278
+ const written = await exportSheets(sheets, { filename });
3279
+ if (!written) onEmpty?.();
3280
+ } catch (error) {
3281
+ onError?.(error);
3282
+ } finally {
3283
+ setIsExporting(false);
3284
+ }
3285
+ }, [tables, parentFullId, sheetNames, filename, onEmpty, onError]);
3286
+ return /* @__PURE__ */ jsxRuntime.jsxs(
3287
+ Button,
3288
+ {
3289
+ type: "button",
3290
+ variant: "outline",
3291
+ size: "sm",
3292
+ className,
3293
+ disabled: disabled || isExporting,
3294
+ onClick: handleClick,
3295
+ children: [
3296
+ isExporting ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "ev-export-icon animate-spin" }) : icon ?? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Download, { className: "ev-export-icon" }),
3297
+ isExporting ? labels.exporting : labels.export
3298
+ ]
3299
+ }
3300
+ );
3301
+ }
2998
3302
  var defaultCell = (content, title) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm text-foreground", title, children: content });
2999
3303
 
3000
3304
  exports.EasyVisionAccordion = EasyVisionAccordion;
@@ -3005,14 +3309,20 @@ exports.EasyVisionCardDescription = EasyVisionCardDescription;
3005
3309
  exports.EasyVisionCardFooter = EasyVisionCardFooter;
3006
3310
  exports.EasyVisionCardHeader = EasyVisionCardHeader;
3007
3311
  exports.EasyVisionCardTitle = EasyVisionCardTitle;
3312
+ exports.EasyVisionExportButton = EasyVisionExportButton;
3008
3313
  exports.EasyVisionInput = EasyVisionInput;
3009
3314
  exports.EasyVisionMultifilter = EasyVisionMultifilter;
3010
3315
  exports.EasyVisionSelector = EasyVisionSelector;
3011
3316
  exports.EasyVisionTable = EasyVisionTable;
3317
+ exports.buildWorkbook = buildWorkbook;
3012
3318
  exports.createLoopbackTableFetcher = createLoopbackTableFetcher;
3013
3319
  exports.defaultCell = defaultCell;
3320
+ exports.downloadBlob = downloadBlob;
3014
3321
  exports.easyVisionRegistry = easyVisionRegistry;
3322
+ exports.exportSheets = exportSheets;
3015
3323
  exports.getSlice = getSlice;
3016
3324
  exports.matchLoopbackWhere = matchLoopbackWhere;
3325
+ exports.sanitizeSheetName = sanitizeSheetName;
3326
+ exports.toExportColumns = toExportColumns;
3017
3327
  //# sourceMappingURL=index.cjs.map
3018
3328
  //# sourceMappingURL=index.cjs.map