@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/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import './easyvision.css';
2
2
  import './EasyVisionTable.css';
3
3
  import * as React9 from 'react';
4
4
  import { createContext, forwardRef, useMemo, useSyncExternalStore, useRef, useEffect, useCallback, useImperativeHandle, useContext, useState, createElement } from 'react';
5
- import { ChevronDown, ChevronUp, Check, Search, X, Plus, ChevronRight, Circle, Calendar as Calendar$1, ChevronLeft, ChevronsUpDown, Loader2, ArrowUp, ArrowDown, ArrowUpDown, Settings2 } from 'lucide-react';
5
+ import { ChevronDown, ChevronUp, Check, Search, X, Plus, ChevronRight, Circle, Calendar as Calendar$1, ChevronLeft, ChevronsUpDown, Loader2, ArrowUp, ArrowDown, ArrowUpDown, Download, Settings2 } from 'lucide-react';
6
6
  import { clsx } from 'clsx';
7
7
  import { twMerge } from 'tailwind-merge';
8
8
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
@@ -19,6 +19,7 @@ import { es } from 'date-fns/locale';
19
19
  import { DayPicker } from 'react-day-picker';
20
20
  import { useReactTable, getCoreRowModel, flexRender } from '@tanstack/react-table';
21
21
  import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
22
+ import ExcelJS from 'exceljs';
22
23
 
23
24
  // index.ts
24
25
  function cn(...inputs) {
@@ -1838,6 +1839,16 @@ function compareByPath(a, b, path, descending) {
1838
1839
  return descending ? bs.localeCompare(as) : as.localeCompare(bs);
1839
1840
  }
1840
1841
 
1842
+ // table/sortLocalRows.ts
1843
+ function sortLocalRows(rows, columns, sort) {
1844
+ if (!sort) return rows;
1845
+ const col = columns.find((c) => c.field === sort.column);
1846
+ if (!col || col.type === "ui") return rows;
1847
+ const next = [...rows];
1848
+ next.sort((a, b) => compareByPath(a, b, col.field, sort.descending));
1849
+ return next;
1850
+ }
1851
+
1841
1852
  // table/useTableData.ts
1842
1853
  function useTableData({
1843
1854
  data,
@@ -1851,12 +1862,7 @@ function useTableData({
1851
1862
  return useMemo(() => {
1852
1863
  let rows = data ?? [];
1853
1864
  if (orderingMode === "local" && sort) {
1854
- const col = columns.find((c) => c.field === sort.column);
1855
- if (col && col.type !== "ui") {
1856
- const next = [...rows];
1857
- next.sort((a, b) => compareByPath(a, b, col.field, sort.descending));
1858
- rows = next;
1859
- }
1865
+ rows = sortLocalRows(rows, columns, sort);
1860
1866
  }
1861
1867
  const totalCount = rows.length;
1862
1868
  if (paginationMode === "local") {
@@ -1866,6 +1872,63 @@ function useTableData({
1866
1872
  return { rows, totalCount };
1867
1873
  }, [data, columns, page, itemsPerPage, sort, paginationMode, orderingMode]);
1868
1874
  }
1875
+
1876
+ // table/applySelection.ts
1877
+ function applySelection(rows, selection, getRowId) {
1878
+ if (selection.scope === "all") {
1879
+ const except = selection.exceptIds;
1880
+ if (!except || Object.keys(except).length === 0) return rows;
1881
+ return rows.filter((row) => !except[getRowId(row)]);
1882
+ }
1883
+ const ids = selection.ids;
1884
+ if (!ids || Object.keys(ids).length === 0) return rows;
1885
+ return rows.filter((row) => ids[getRowId(row)]);
1886
+ }
1887
+
1888
+ // table/columnVisibility.ts
1889
+ function resolveColumnVisibility(columns, sliceVisibility) {
1890
+ const defaults = {};
1891
+ for (const column of columns) {
1892
+ if (column.initiallyHidden) defaults[column.field] = false;
1893
+ }
1894
+ return { ...defaults, ...sliceVisibility };
1895
+ }
1896
+ var isColumnVisible = (visibility, field) => visibility[field] !== false;
1897
+
1898
+ // table/fetchAllRows.ts
1899
+ var FETCH_ALL_PAGE_SIZE = 200;
1900
+ var mergeFilters = (externalFilter, multifilterQuery) => externalFilter || multifilterQuery ? {
1901
+ ...multifilterQuery,
1902
+ where: {
1903
+ ...externalFilter?.where ?? {},
1904
+ ...multifilterQuery?.where ?? {}
1905
+ }
1906
+ } : void 0;
1907
+ async function fetchAllRows({
1908
+ fetchData,
1909
+ filter,
1910
+ sort,
1911
+ idsOnly = false,
1912
+ pageSize = FETCH_ALL_PAGE_SIZE,
1913
+ shouldContinue
1914
+ }) {
1915
+ const collected = [];
1916
+ let knownTotal = Infinity;
1917
+ for (let page = 1; collected.length < knownTotal; page++) {
1918
+ const result = await fetchData({
1919
+ page,
1920
+ itemsPerPage: pageSize,
1921
+ sort,
1922
+ filter,
1923
+ idsOnly
1924
+ });
1925
+ if (shouldContinue && !shouldContinue()) return null;
1926
+ knownTotal = result.totalCount;
1927
+ collected.push(...result.rows);
1928
+ if (result.rows.length < pageSize) break;
1929
+ }
1930
+ return collected;
1931
+ }
1869
1932
  var DropdownMenu = DropdownMenuPrimitive.Root;
1870
1933
  var DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
1871
1934
  var DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
@@ -2257,6 +2320,48 @@ function matchLeaf(value, condition) {
2257
2320
  }
2258
2321
  return true;
2259
2322
  }
2323
+
2324
+ // export/sources.ts
2325
+ var sources = /* @__PURE__ */ new Map();
2326
+ var registerExportSource = (fullId, source) => {
2327
+ sources.set(fullId, source);
2328
+ };
2329
+ var unregisterExportSource = (fullId) => {
2330
+ sources.delete(fullId);
2331
+ };
2332
+ var getExportSource = (fullId) => sources.get(fullId);
2333
+ var resolveExportSource = (parentFullId, tableId) => getExportSource(childFullIdOf(parentFullId, tableId, "table")) ?? getExportSource(tableId);
2334
+
2335
+ // export/exportColumns.ts
2336
+ var toExportCellValue = (raw) => {
2337
+ if (raw == null) return null;
2338
+ if (Array.isArray(raw)) return raw.join(", ");
2339
+ if (raw instanceof Date) return raw;
2340
+ const kind = typeof raw;
2341
+ if (kind === "string" || kind === "number" || kind === "boolean") {
2342
+ return raw;
2343
+ }
2344
+ return String(raw);
2345
+ };
2346
+ var isExportable = (column) => column.exportable ?? column.type !== "ui";
2347
+ var exportHeaderOf = (column) => column.exportHeader ?? (typeof column.header === "string" ? column.header : column.field);
2348
+ function toExportColumns(columns, isVisible) {
2349
+ return columns.filter((column) => isExportable(column) && isVisible(column.field)).map((column) => {
2350
+ const exportValue = column.exportValue;
2351
+ const exportStyle = column.exportStyle;
2352
+ const field = column.field;
2353
+ const isUi = column.type === "ui";
2354
+ return {
2355
+ header: exportHeaderOf(column),
2356
+ getValue: (item) => {
2357
+ if (exportValue) return toExportCellValue(exportValue(item));
2358
+ if (isUi) return null;
2359
+ return toExportCellValue(getByPath(item, field));
2360
+ },
2361
+ getStyle: exportStyle ? (value, item) => exportStyle(value, item) : void 0
2362
+ };
2363
+ });
2364
+ }
2260
2365
  var DEFAULT_LABELS2 = {
2261
2366
  rowsPerPage: "Resultados por p\xE1gina:",
2262
2367
  results: "Resultados",
@@ -2373,14 +2478,7 @@ function EasyVisionTable(props) {
2373
2478
  const seq = ++fetchSeqRef.current;
2374
2479
  setApiLoading(true);
2375
2480
  try {
2376
- const mfQuery = lastSnapshotRef.current?.query;
2377
- const merged = externalFilter || mfQuery ? {
2378
- ...mfQuery,
2379
- where: {
2380
- ...externalFilter?.where ?? {},
2381
- ...mfQuery?.where ?? {}
2382
- }
2383
- } : void 0;
2481
+ const merged = mergeFilters(externalFilter, lastSnapshotRef.current?.query);
2384
2482
  const result = await fetchData({
2385
2483
  page,
2386
2484
  itemsPerPage,
@@ -2404,38 +2502,23 @@ function EasyVisionTable(props) {
2404
2502
  const seq = ++eagerSeqRef.current;
2405
2503
  setIsResolvingEager(true);
2406
2504
  try {
2407
- const mfQuery = lastSnapshotRef.current?.query;
2408
- const merged = externalFilter || mfQuery ? {
2409
- ...mfQuery,
2410
- where: {
2411
- ...externalFilter?.where ?? {},
2412
- ...mfQuery?.where ?? {}
2413
- }
2414
- } : void 0;
2415
- const PAGE_SIZE = 200;
2505
+ const fetched = await fetchAllRows({
2506
+ fetchData,
2507
+ filter: mergeFilters(externalFilter, lastSnapshotRef.current?.query),
2508
+ sort,
2509
+ idsOnly: !collectRows,
2510
+ shouldContinue: () => seq === eagerSeqRef.current
2511
+ });
2512
+ if (fetched === null || seq !== eagerSeqRef.current) return;
2416
2513
  const ids = [];
2417
2514
  const rowsAcc = [];
2418
- let knownTotal = Infinity;
2419
- for (let p = 1; ids.length < knownTotal; p++) {
2420
- const result = await fetchData({
2421
- page: p,
2422
- itemsPerPage: PAGE_SIZE,
2423
- sort,
2424
- filter: merged,
2425
- idsOnly: !collectRows
2426
- });
2427
- if (seq !== eagerSeqRef.current) return;
2428
- knownTotal = result.totalCount;
2429
- for (const row of result.rows) {
2430
- const rid = getRowId(row);
2431
- if (rid) {
2432
- ids.push(rid);
2433
- if (collectRows) rowsAcc.push(row);
2434
- }
2515
+ for (const row of fetched) {
2516
+ const rid = getRowId(row);
2517
+ if (rid) {
2518
+ ids.push(rid);
2519
+ if (collectRows) rowsAcc.push(row);
2435
2520
  }
2436
- if (result.rows.length < PAGE_SIZE) break;
2437
2521
  }
2438
- if (seq !== eagerSeqRef.current) return;
2439
2522
  setEagerAllIds(ids);
2440
2523
  if (collectRows) setEagerAllRows(rowsAcc);
2441
2524
  } finally {
@@ -2500,17 +2583,62 @@ function EasyVisionTable(props) {
2500
2583
  };
2501
2584
  return [checkboxCol, ...tanstackColumns];
2502
2585
  }, [enableRowSelection, tanstackColumns]);
2503
- const visibilityDefaults = useMemo(() => {
2504
- const v = {};
2505
- for (const c of columns) {
2506
- if (c.initiallyHidden) v[c.field] = false;
2507
- }
2508
- return v;
2509
- }, [columns]);
2510
2586
  const columnVisibility = useMemo(
2511
- () => ({ ...visibilityDefaults, ...slice.columnVisibility }),
2512
- [visibilityDefaults, slice.columnVisibility]
2587
+ () => resolveColumnVisibility(columns, slice.columnVisibility),
2588
+ [columns, slice.columnVisibility]
2513
2589
  );
2590
+ const exportStateRef = useRef({
2591
+ columns,
2592
+ columnVisibility,
2593
+ selection,
2594
+ fetchData,
2595
+ externalFilter,
2596
+ sort,
2597
+ filteredData,
2598
+ isApi,
2599
+ getRowId
2600
+ });
2601
+ exportStateRef.current = {
2602
+ columns,
2603
+ columnVisibility,
2604
+ selection,
2605
+ fetchData,
2606
+ externalFilter,
2607
+ sort,
2608
+ filteredData,
2609
+ isApi,
2610
+ getRowId
2611
+ };
2612
+ useEffect(() => {
2613
+ registerExportSource(fullId, {
2614
+ sheetName: id,
2615
+ getColumns: () => {
2616
+ const state = exportStateRef.current;
2617
+ return toExportColumns(
2618
+ state.columns,
2619
+ (field) => isColumnVisible(state.columnVisibility, field)
2620
+ );
2621
+ },
2622
+ getRows: async () => {
2623
+ const state = exportStateRef.current;
2624
+ let all;
2625
+ if (state.isApi && state.fetchData) {
2626
+ all = await fetchAllRows({
2627
+ fetchData: state.fetchData,
2628
+ filter: mergeFilters(
2629
+ state.externalFilter,
2630
+ lastSnapshotRef.current?.query
2631
+ ),
2632
+ sort: state.sort
2633
+ }) ?? [];
2634
+ } else {
2635
+ all = sortLocalRows(state.filteredData ?? [], state.columns, state.sort);
2636
+ }
2637
+ return applySelection(all, state.selection, state.getRowId);
2638
+ }
2639
+ });
2640
+ return () => unregisterExportSource(fullId);
2641
+ }, [fullId, id]);
2514
2642
  const resizableFields = useMemo(() => {
2515
2643
  const s = /* @__PURE__ */ new Set();
2516
2644
  for (const c of columns) if (c.resizable) s.add(c.field);
@@ -2565,6 +2693,14 @@ function EasyVisionTable(props) {
2565
2693
  getCoreRowModel: getCoreRowModel(),
2566
2694
  manualPagination: true,
2567
2695
  manualSorting: true,
2696
+ // TanStack picks the first sort direction per column by sniffing row 0 of
2697
+ // the *current* page (`getAutoSortDir`: string → asc, anything else → desc).
2698
+ // With server-side data that row changes between clicks, so the asc/desc/off
2699
+ // cycle collapses — e.g. a nullable date column whose page-1 ASC result leads
2700
+ // with a null row flips firstSortDir to 'desc' and the next click removes the
2701
+ // sort instead of going descending. Pin it so the cycle is always off → asc
2702
+ // → desc → off, on every page.
2703
+ sortDescFirst: false,
2568
2704
  enableColumnResizing: true,
2569
2705
  columnResizeMode: "onChange",
2570
2706
  pageCount: Math.ceil(totalCount / itemsPerPage),
@@ -2970,8 +3106,173 @@ function EasyVisionTable(props) {
2970
3106
  ] })
2971
3107
  ] }) });
2972
3108
  }
3109
+ var HEADER_FILL_ARGB = "FFCCCCCC";
3110
+ var MIN_COLUMN_WIDTH = 10;
3111
+ var COLUMN_WIDTH_PADDING = 2;
3112
+ var XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
3113
+ var INVALID_SHEET_CHARS = /[*?:\\/[\]]/g;
3114
+ var MAX_SHEET_NAME = 31;
3115
+ var FALLBACK_SHEET_NAME = "Hoja";
3116
+ var sanitizeSheetName = (name) => name.replace(INVALID_SHEET_CHARS, "-").substring(0, MAX_SHEET_NAME) || FALLBACK_SHEET_NAME;
3117
+ var uniqueSheetName = (raw, taken) => {
3118
+ const base = sanitizeSheetName(raw);
3119
+ if (!taken.has(base)) {
3120
+ taken.add(base);
3121
+ return base;
3122
+ }
3123
+ for (let n = 2; ; n++) {
3124
+ const suffix = `_${n}`;
3125
+ const candidate = base.substring(0, MAX_SHEET_NAME - suffix.length) + suffix;
3126
+ if (!taken.has(candidate)) {
3127
+ taken.add(candidate);
3128
+ return candidate;
3129
+ }
3130
+ }
3131
+ };
3132
+ var downloadBlob = (blob, filename) => {
3133
+ const url = URL.createObjectURL(blob);
3134
+ const anchor = document.createElement("a");
3135
+ anchor.href = url;
3136
+ anchor.download = filename;
3137
+ document.body.appendChild(anchor);
3138
+ anchor.click();
3139
+ anchor.remove();
3140
+ setTimeout(() => URL.revokeObjectURL(url), 0);
3141
+ };
3142
+ var autoFitColumns = (worksheet) => {
3143
+ worksheet.columns.forEach((column) => {
3144
+ let longest = 0;
3145
+ column.eachCell?.({ includeEmpty: false }, (cell) => {
3146
+ const length = cell.value instanceof Date ? cell.value.toISOString().length : cell.text.length;
3147
+ if (length > longest) longest = length;
3148
+ });
3149
+ column.width = Math.max(MIN_COLUMN_WIDTH, longest + COLUMN_WIDTH_PADDING);
3150
+ });
3151
+ };
3152
+ async function buildWorkbook(sheets) {
3153
+ const usable = sheets.filter(
3154
+ (sheet) => sheet.rows.length > 0 && sheet.columns.length > 0
3155
+ );
3156
+ if (usable.length === 0) return null;
3157
+ const workbook = new ExcelJS.Workbook();
3158
+ const takenNames = /* @__PURE__ */ new Set();
3159
+ for (const sheet of usable) {
3160
+ const worksheet = workbook.addWorksheet(uniqueSheetName(sheet.name, takenNames));
3161
+ const headerRow = worksheet.addRow(sheet.columns.map((c) => c.header));
3162
+ headerRow.eachCell((cell) => {
3163
+ cell.fill = {
3164
+ type: "pattern",
3165
+ pattern: "solid",
3166
+ fgColor: { argb: HEADER_FILL_ARGB }
3167
+ };
3168
+ cell.font = { bold: true };
3169
+ });
3170
+ for (const item of sheet.rows) {
3171
+ const values = sheet.columns.map((column) => column.getValue(item));
3172
+ const row = worksheet.addRow(values);
3173
+ sheet.columns.forEach((column, index) => {
3174
+ const style = column.getStyle?.(values[index], item);
3175
+ if (!style) return;
3176
+ const cell = row.getCell(index + 1);
3177
+ if (style.fill) {
3178
+ cell.fill = {
3179
+ type: "pattern",
3180
+ pattern: "solid",
3181
+ fgColor: { argb: style.fill }
3182
+ };
3183
+ }
3184
+ if (style.fontColor || style.bold) {
3185
+ cell.font = {
3186
+ bold: !!style.bold,
3187
+ ...style.fontColor ? { color: { argb: style.fontColor } } : {}
3188
+ };
3189
+ }
3190
+ });
3191
+ }
3192
+ autoFitColumns(worksheet);
3193
+ }
3194
+ return workbook;
3195
+ }
3196
+ async function exportSheets(sheets, options) {
3197
+ const workbook = await buildWorkbook(sheets);
3198
+ if (!workbook) return false;
3199
+ const buffer = await workbook.xlsx.writeBuffer();
3200
+ const blob = new Blob([buffer], { type: XLSX_MIME });
3201
+ const filename = `${options.filename}_${(/* @__PURE__ */ new Date()).toISOString()}.xlsx`;
3202
+ (options.download ?? downloadBlob)(blob, filename);
3203
+ return true;
3204
+ }
3205
+ var DEFAULT_LABELS3 = {
3206
+ export: "Exportar",
3207
+ exporting: "Exportando..."
3208
+ };
3209
+ function EasyVisionExportButton({
3210
+ tables,
3211
+ filename,
3212
+ sheetNames,
3213
+ labels: labelOverrides,
3214
+ onError,
3215
+ onEmpty,
3216
+ disabled = false,
3217
+ className,
3218
+ icon
3219
+ }) {
3220
+ const labels = { ...DEFAULT_LABELS3, ...labelOverrides };
3221
+ const parentFullId = useParentFullId();
3222
+ const [isExporting, setIsExporting] = useState(false);
3223
+ const handleClick = useCallback(async () => {
3224
+ setIsExporting(true);
3225
+ try {
3226
+ const resolved = tables.map((tableId) => ({
3227
+ tableId,
3228
+ source: resolveExportSource(parentFullId, tableId)
3229
+ }));
3230
+ const unresolved = resolved.filter((r) => !r.source).map((r) => r.tableId);
3231
+ if (unresolved.length > 0 && unresolved.length < tables.length) {
3232
+ onError?.(
3233
+ new Error(
3234
+ `EasyVisionExportButton: could not resolve table id(s): ${unresolved.join(", ")}`
3235
+ )
3236
+ );
3237
+ return;
3238
+ }
3239
+ const sheets = [];
3240
+ for (const { tableId, source } of resolved) {
3241
+ if (!source) continue;
3242
+ const columns = source.getColumns();
3243
+ if (columns.length === 0) continue;
3244
+ sheets.push({
3245
+ name: sheetNames?.[tableId] ?? source.sheetName,
3246
+ columns,
3247
+ rows: await source.getRows()
3248
+ });
3249
+ }
3250
+ const written = await exportSheets(sheets, { filename });
3251
+ if (!written) onEmpty?.();
3252
+ } catch (error) {
3253
+ onError?.(error);
3254
+ } finally {
3255
+ setIsExporting(false);
3256
+ }
3257
+ }, [tables, parentFullId, sheetNames, filename, onEmpty, onError]);
3258
+ return /* @__PURE__ */ jsxs(
3259
+ Button,
3260
+ {
3261
+ type: "button",
3262
+ variant: "outline",
3263
+ size: "sm",
3264
+ className,
3265
+ disabled: disabled || isExporting,
3266
+ onClick: handleClick,
3267
+ children: [
3268
+ isExporting ? /* @__PURE__ */ jsx(Loader2, { className: "ev-export-icon animate-spin" }) : icon ?? /* @__PURE__ */ jsx(Download, { className: "ev-export-icon" }),
3269
+ isExporting ? labels.exporting : labels.export
3270
+ ]
3271
+ }
3272
+ );
3273
+ }
2973
3274
  var defaultCell = (content, title) => /* @__PURE__ */ jsx("span", { className: "text-sm text-foreground", title, children: content });
2974
3275
 
2975
- export { EasyVisionAccordion, EasyVisionAccordionItem, EasyVisionCard, EasyVisionCardContent, EasyVisionCardDescription, EasyVisionCardFooter, EasyVisionCardHeader, EasyVisionCardTitle, EasyVisionInput, EasyVisionMultifilter, EasyVisionSelector, EasyVisionTable, createLoopbackTableFetcher, defaultCell, easyVisionRegistry, getSlice, matchLoopbackWhere };
3276
+ export { EasyVisionAccordion, EasyVisionAccordionItem, EasyVisionCard, EasyVisionCardContent, EasyVisionCardDescription, EasyVisionCardFooter, EasyVisionCardHeader, EasyVisionCardTitle, EasyVisionExportButton, EasyVisionInput, EasyVisionMultifilter, EasyVisionSelector, EasyVisionTable, buildWorkbook, createLoopbackTableFetcher, defaultCell, downloadBlob, easyVisionRegistry, exportSheets, getSlice, matchLoopbackWhere, sanitizeSheetName, toExportColumns };
2976
3277
  //# sourceMappingURL=index.js.map
2977
3278
  //# sourceMappingURL=index.js.map