@telamonjs/ui 1.3.1 → 1.4.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.
Files changed (59) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +7 -8
  3. package/dist/components/data/DataTableActions.js +4 -3
  4. package/dist/data/ExportMenu.js +6 -3
  5. package/dist/data/InfiniteList.js +6 -2
  6. package/dist/data/datatable/sort-field.d.ts +14 -0
  7. package/dist/data/datatable/sort-field.js +24 -0
  8. package/dist/data/datatable/useDataTableInstance.js +3 -2
  9. package/dist/data/exportUtils.d.ts +14 -9
  10. package/dist/data/exportUtils.js +56 -56
  11. package/dist/data/missing-peer.d.ts +17 -0
  12. package/dist/data/missing-peer.js +22 -0
  13. package/dist/data/xlsx-writer.d.ts +24 -0
  14. package/dist/data/xlsx-writer.js +141 -0
  15. package/dist/exports/types-constants.d.ts +1 -1
  16. package/dist/exports/types-constants.js +1 -1
  17. package/dist/i18n/messages/en/data.d.ts +1 -0
  18. package/dist/i18n/messages/en/data.js +1 -0
  19. package/dist/i18n/messages/en/index.d.ts +3 -0
  20. package/dist/i18n/messages/en/queue.d.ts +2 -0
  21. package/dist/i18n/messages/en/queue.js +3 -1
  22. package/dist/i18n/messages/es/data.d.ts +1 -0
  23. package/dist/i18n/messages/es/data.js +1 -0
  24. package/dist/i18n/messages/es/index.d.ts +3 -0
  25. package/dist/i18n/messages/es/queue.d.ts +2 -0
  26. package/dist/i18n/messages/es/queue.js +3 -1
  27. package/dist/i18n/messages/pt-BR/data.d.ts +1 -0
  28. package/dist/i18n/messages/pt-BR/data.js +1 -0
  29. package/dist/i18n/messages/pt-BR/index.d.ts +3 -0
  30. package/dist/i18n/messages/pt-BR/queue.d.ts +2 -0
  31. package/dist/i18n/messages/pt-BR/queue.js +3 -1
  32. package/dist/i18n/use-t.d.ts +3 -0
  33. package/dist/pages/ListPage.js +6 -1
  34. package/dist/queue/components/DispatchJobModal.js +157 -115
  35. package/dist/queue/components/JobEventTimeline.js +321 -210
  36. package/dist/queue/hooks/use-queue-events-timeline.d.ts +7 -1
  37. package/dist/queue/hooks/use-queue-events-timeline.js +14 -43
  38. package/dist/queue/hooks/use-queue-sse.js +3 -1
  39. package/dist/queue/types.d.ts +2 -0
  40. package/dist/server/pagination/factory.js +5 -1
  41. package/dist/server/pagination/types.d.ts +6 -2
  42. package/dist/server/pagination/utils.d.ts +6 -3
  43. package/dist/server/pagination/utils.js +13 -7
  44. package/dist/server/prisma-helpers.d.ts +27 -19
  45. package/dist/server/prisma-helpers.js +37 -19
  46. package/dist/stores/datatable-store.d.ts +0 -4
  47. package/dist/stores/datatable-store.js +0 -5
  48. package/dist/stores/form-store.d.ts +5 -0
  49. package/dist/stores/form-store.js +8 -4
  50. package/dist/stores/index.d.ts +1 -1
  51. package/dist/stores/index.js +1 -3
  52. package/dist/stores/sidebar-store.d.ts +1 -1
  53. package/dist/types/actions.d.ts +4 -1
  54. package/dist/types/crud.d.ts +14 -1
  55. package/dist/types/system-config.d.ts +5 -0
  56. package/dist/ui/chart.d.ts +22 -27
  57. package/dist/ui/chart.js +2 -8
  58. package/dist/ui/form.d.ts +1 -1
  59. package/package.json +67 -64
package/CHANGELOG.md CHANGED
@@ -1,5 +1,99 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - f87e9ae: Sort by data paths: opt-in `list.sortParam` and server helpers that read both wire forms.
8
+
9
+ **Client.** `list.sortParam: 'path'` makes `ListPage` send a column's `accessorKey` with its dots
10
+ (`customer.name`, `_count.items`) as `sortBy`, instead of TanStack's column id (`customer_name`,
11
+ `_count_items`). Columns without an `accessorKey` keep sending their `id`. It applies to `queryFn`,
12
+ `exportAll`, `list.onExport`, `toolbarContent` and the `urlSync` URL. The default stays `'id'`, so
13
+ nothing changes on the wire until a list opts in; `'path'` becomes the default in the next major.
14
+ Stored sorts accept both forms in both modes: `defaultSortBy: 'customer.name'` and saved views now
15
+ highlight the right header (before, a dotted stored field showed no arrow and a header click added
16
+ a second sort entry).
17
+
18
+ **Backend contract.** `'id'`: `sortBy` is the column id, a dotted `accessorKey` with `.` → `_`.
19
+ `'path'`: `sortBy` is the data path; order `_count.<relation>` with `{ <relation>: { _count: dir } }`.
20
+ Before opting in, make sure the endpoint accepts the dotted form: a whitelist keyed by
21
+ `customer_name` falls back to its default order for `customer.name` — add the dotted key alongside.
22
+
23
+ **Server helpers.** `buildPrismaOrderBy` / `buildPrismaOrderByMulti` take an optional
24
+ `sortableFields` and read both forms: a value with a dot is used as-is (underscores kept, e.g.
25
+ `order_item.created_at`); `_count.x` / `_count_x` produce Prisma's relation-count order; a listed
26
+ value is used as-is (`created_at` stays a column); other underscored values are decoded as legacy
27
+ ids (`customer_name` → `customer.name`) — with `sortableFields`, only when the decoded path is listed.
28
+ `createPaginatedService` passes its `sortableFields` through, and `sortableFields` now accepts a
29
+ legacy id whose dotted form is listed (a dotted entry was rejected before, contrary to its docs).
30
+
31
+ Behaviour changes for helper callers: `_count`/leading-underscore fields now build valid Prisma
32
+ (they produced an empty key before); a value mixing dots and underscores is no longer re-split on
33
+ its underscores; a `sortableFields` entry in `_` form (`customer_name`) is now taken as a scalar —
34
+ list the dotted path (`customer.name`) instead.
35
+
36
+ - f32a4c4: Row actions `display.mode: 'auto'` now does what it promised: every action goes into the "⋯" menu on mobile (below 768px, the `useIsMobile` breakpoint) and stays inline (with `maxInline`) elsewhere. It used to behave exactly like `'inline'`.
37
+ - 4ea79f7: Export peers are lazy and optional.
38
+
39
+ - `papaparse` is no longer a peer: `exportToCSV` writes RFC 4180 CSV itself (UTF-8 BOM, CRLF, same quoting). Columns that share a header no longer collapse into one.
40
+ - `jspdf` and `jspdf-autotable` are now **optional** peers (`peerDependenciesMeta`), loaded with `import()` only when a PDF is exported. Without them the app still builds, and the PDF export fails with a localized toast naming the packages to install (new message `data.exportMissingPeer`) instead of a module-not-found error. `exportToPDF` returns a `Promise<void>` (it returned `void`) and rejects with an error naming both packages.
41
+ - `scripts/check-lazy-deps.mjs` now fails the build if any file in `dist/` statically imports an optional peer.
42
+
43
+ **Apps:** nothing to change; PDF export keeps working where `jspdf` + `jspdf-autotable` are installed. Apps that never export PDF can drop them, and every app can drop `papaparse` and `@types/papaparse` unless it uses them directly. New apps from `create-telamonjs-app` keep the `jspdf` pair and no longer list `papaparse`.
44
+
45
+ - 21eef48: Excel export no longer depends on SheetJS: the `xlsx` peer is gone. npm only carries `xlsx` 0.18.5, flagged by CVE-2023-30533 (prototype pollution) and CVE-2024-22363 (ReDoS), and the fixed builds are published outside the registry. `exportToExcel` now writes the workbook itself (OOXML parts, zipped with the platform `CompressionStream`), with no dependency at all.
46
+
47
+ - Same output: columns, headers, cell values, filename, sheet name and 10–50 character column widths. The header row is now really bold on a light gray fill (SheetJS community silently ignored that styling).
48
+ - Sheet names follow Excel's rules instead of throwing: at most 31 characters, `\ / ? * [ ] :` become spaces.
49
+ - `exportToExcel` and `exportTableData` return a `Promise<void>` that resolves once the download starts (they returned `void`); await it to catch failures.
50
+
51
+ **Apps:** nothing to change. `xlsx` can be removed from the app's dependencies (`pnpm remove xlsx`) unless the app uses it directly. New apps from `create-telamonjs-app` no longer list it.
52
+
53
+ ### Patch Changes
54
+
55
+ - b6dcc0b: `ChartTooltipContent` and `ChartLegendContent` type their `payload` (and the tooltip's `active`
56
+ and `label`) with recharts' own `TooltipContentProps` and `LegendPayload` instead of a hand-written
57
+ copy, so the payload recharts hands to `content` type-checks as-is and future recharts minors no
58
+ longer break the build. `formatter` now receives recharts' documented fifth argument, the whole
59
+ tooltip payload, instead of the hovered data row (still available as `item.payload`).
60
+ - 5abed37: Raise the minimum versions of runtime dependencies to the current minors (no peer range changes).
61
+
62
+ - `@telamonjs/ui`: `recharts` `~3.3.0` → `~3.11.0`; the `@radix-ui/react-*` primitives,
63
+ `@tiptap/*` `^3.35.0`, `react-aria` `^3.53.1`, `react-stately` `^3.51.0`, `zustand` `^5.1.0`,
64
+ `date-fns` `^4.4.0`, `dompurify` `^3.4.18`, `react-grid-layout` `^2.3.0`, `react-is` `^19.3.1`,
65
+ `@tanstack/react-virtual` `^3.14.26`, `@uiw/react-textarea-code-editor` `^3.1.3` and
66
+ `@vis.gl/react-google-maps` `^1.10.2`.
67
+ - `@telamonjs/cli`: `fs-extra` `^11.4.1`. Apps created by `create-telamonjs-app` pin the same
68
+ updated versions (`@radix-ui/*`, `@auth/prisma-adapter`, `date-fns`, `zustand`, `postcss`,
69
+ `autoprefixer`, `prettier`, `prettier-plugin-tailwindcss`, `tsx` and friends).
70
+
71
+ - 9600019: `DispatchJobModal` sends an `array` schema field as an array: the input (whose placeholder asks
72
+ for `["id1", "id2"]`) is parsed as JSON instead of being dispatched as the raw string, and a value
73
+ that is not a JSON array is refused with the "invalid JSON" toast. Each field label is now
74
+ associated with its input.
75
+ - 913a234: `useFormStore().setFormData()` (which `useForm(formId, initialData)` and `ZustandForm` call to load
76
+ the record) no longer marks the form dirty. Loading data is the baseline, like react-hook-form's
77
+ `reset()`: `isDirty` / `useForms().anyDirty` now turn `true` only after a field is edited
78
+ (`updateField`), so they can drive an unsaved-changes guard. Before, every form was dirty as soon as
79
+ it opened.
80
+ - 7a768f5: `ZustandForm` / `useForm().validate()` accept `0` in a required field (it was reported as
81
+ missing) and reject an empty array (an empty required multiselect passed). `useForms().validateAll()`
82
+ now validates every form instead of stopping at the first invalid one, so later wizard steps get
83
+ their errors too.
84
+ - 4cbf64c: Queue dashboard real-time timeline (`QueueDashboard`): job rows are now buttons (Tab, Enter/Space
85
+ open the details, visible focus ring) inside a list, and the row actions work: retry calls the
86
+ adapter's `retryJob` (failed jobs only; hidden for `manualRetry: false` queues), remove calls
87
+ `removeJob` after an inline confirmation (not offered for active jobs), both with the same toasts
88
+ as the jobs list, and both hidden under `readOnly`. The actions also appear on keyboard focus, not
89
+ only on hover. The hardcoded `#REPEAT` tag is gone; a "Recurring" badge marks only job scheduler /
90
+ repeatable iterations. The timeline details (and its expanded view) and `DispatchJobModal` close
91
+ on Escape and are announced as modal dialogs.
92
+ - Updated dependencies [2d019f6]
93
+ - Updated dependencies [ac040f3]
94
+ - Updated dependencies [06e660f]
95
+ - @telamonjs/logger@1.1.0
96
+
3
97
  ## 1.3.1
4
98
 
5
99
  ### Patch Changes
package/README.md CHANGED
@@ -15,31 +15,30 @@ existing Next.js app:
15
15
 
16
16
  <!-- generated:peers -->
17
17
  ```bash
18
- pnpm add @telamonjs/ui framer-motion jspdf jspdf-autotable next next-auth papaparse react react-dom react-hook-form sonner xlsx zod next-intl @tanstack/react-query
18
+ pnpm add @telamonjs/ui framer-motion next next-auth react react-dom react-hook-form sonner zod next-intl @tanstack/react-query
19
19
  ```
20
20
 
21
21
  | Peer dependency | Range |
22
22
  | --- | --- |
23
23
  | `framer-motion` | `^11.0.0 \|\| ^12.0.0` |
24
- | `jspdf` | `^4.2.1` |
25
- | `jspdf-autotable` | `^5.0.7` |
26
24
  | `next` | `^15.5.29 \|\| ^16.4.6` |
27
25
  | `next-auth` | `^5.0.0-beta.20` |
28
- | `papaparse` | `^5.5.0` |
29
26
  | `react` | `^18.0.0 \|\| ^19.0.0` |
30
27
  | `react-dom` | `^18.0.0 \|\| ^19.0.0` |
31
28
  | `react-hook-form` | `^7.0.0` |
32
29
  | `sonner` | `^1.7.1 \|\| ^2.0.7` |
33
- | `xlsx` | `^0.18.0` |
34
30
  | `zod` | `^3.0.0` |
35
31
  | `next-intl` | `^4.14.0` |
36
32
  | `@tanstack/react-query` | `^5.90.2` |
37
33
  | `@prisma/client` (optional) | `^5.0.0 \|\| ^6.0.0` |
34
+ | `jspdf` (optional) | `^4.2.1` |
35
+ | `jspdf-autotable` (optional) | `^5.0.7` |
38
36
  <!-- /generated:peers -->
39
37
 
40
38
  `DashboardGrid` needs the `react-grid-layout` stylesheet
41
- (`import 'react-grid-layout/css/styles.css'`), and `@prisma/client` is only needed for the
42
- `./server` pagination helpers. Then load the styles and the Tailwind preset:
39
+ (`import 'react-grid-layout/css/styles.css'`), `@prisma/client` is only needed for the
40
+ `./server` pagination helpers, and `jspdf` + `jspdf-autotable` only for PDF export (Excel and
41
+ CSV export need no extra package). Then load the styles and the Tailwind preset:
43
42
 
44
43
  ```tsx
45
44
  // app/layout.tsx
@@ -92,7 +91,7 @@ async `loadField`), `'multiselect'`, `'richtext'` and 31 more; there is no
92
91
  | Data | `DataTable`, `VirtualDataTable`, `InfiniteList`, bulk actions, Excel/CSV/PDF export, `QueryErrorState` (error + pending "Try again" for your own `useQuery`) |
93
92
  | Dashboards and charts | `DashboardGrid`, `DashboardShell`, `StatCard`, `ChartWidget`, `LineChart`, `BarChart`, `PieChart`, `AreaChart`, `KPICard` |
94
93
  | Queue UI | `@telamonjs/ui/queue`: `QueueTabbedDashboard`, `QueueApiProvider`, `createNestJSAdapter`, a frontend for `@telamonjs/queue` |
95
- | Server | `@telamonjs/ui/server`: `createPaginationContext`, `buildPrismaOrderBy`, `createPaginatedResponse`, `revalidatePathAction` |
94
+ | Server | `@telamonjs/ui/server`: `createPaginationContext`, `buildPrismaOrderBy` (both `list.sortParam` wire forms, `_count.<relation>`), `createPaginatedResponse`, `revalidatePathAction` |
96
95
  | i18n | `@telamonjs/ui/i18n`: `msg`, `useText`, `LocaleSwitcher`; UI copy ships in pt-BR (default), en and es |
97
96
 
98
97
  Menu icons are strings resolved through `setIconResolver()`: the icon registry
@@ -20,6 +20,7 @@ import { actionEnabled, actionGranted, actionVisible } from "./action-access.js"
20
20
  import { getIconFromName } from "../../utils/icon.js";
21
21
  import { TEST_IDS, getActionAccessibilityAttrs } from "../../utils/test-ids.js";
22
22
  import { useTelamonjsT, useText } from "../../i18n/use-t.js";
23
+ import { useIsMobile } from "../../hooks/use-mobile.js";
23
24
  import { isMessageRef } from "../../i18n/msg.js";
24
25
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
25
26
  function getEntityLabel(row) {
@@ -329,7 +330,9 @@ function DataTableActions({
329
330
  }),
330
331
  [row.original, router, handleActionComplete, text, t]
331
332
  );
332
- const displayMode = config.display?.mode || "inline";
333
+ const isMobile = useIsMobile();
334
+ const requestedMode = config.display?.mode || "inline";
335
+ const displayMode = requestedMode === "auto" ? isMobile ? "dropdown" : "inline" : requestedMode;
333
336
  const maxInline = config.display?.maxInline || 999;
334
337
  const spacing = config.display?.spacing || "normal";
335
338
  const { inlineActions, overflowActions } = useMemo(() => {
@@ -339,8 +342,6 @@ function DataTableActions({
339
342
  overflowActions: [...filteredInlineActions, ...filteredDropdownActions]
340
343
  };
341
344
  }
342
- if (displayMode === "auto") {
343
- }
344
345
  const inline = filteredInlineActions.slice(0, maxInline);
345
346
  const overflow = [
346
347
  ...filteredInlineActions.slice(maxInline),
@@ -25,6 +25,7 @@ import {
25
25
  DropdownMenuSubTrigger,
26
26
  DropdownMenuSubContent
27
27
  } from "../ui/dropdown-menu.js";
28
+ import { MissingPeerError } from "./missing-peer.js";
28
29
  import { toast } from "sonner";
29
30
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
30
31
  function ExportMenu({
@@ -149,7 +150,7 @@ function ExportMenu({
149
150
  const common = { includeHiddenColumns: false, appendDate, t, locale };
150
151
  switch (format) {
151
152
  case "excel":
152
- exportToExcel(dataToExport, columns, filename, {
153
+ await exportToExcel(dataToExport, columns, filename, {
153
154
  ...common,
154
155
  sheetName
155
156
  });
@@ -158,7 +159,7 @@ function ExportMenu({
158
159
  exportToCSV(dataToExport, columns, filename, common);
159
160
  break;
160
161
  case "pdf":
161
- exportToPDF(dataToExport, columns, filename, {
162
+ await exportToPDF(dataToExport, columns, filename, {
162
163
  ...common,
163
164
  ...pdfOptions,
164
165
  orientation: pdfOptions.orientation || "landscape"
@@ -173,7 +174,9 @@ function ExportMenu({
173
174
  logger.error("Export error", {
174
175
  error: error instanceof Error ? error : String(error)
175
176
  });
176
- toast.error(t("data.exportError"));
177
+ toast.error(
178
+ error instanceof MissingPeerError ? t("data.exportMissingPeer", { packages: error.packages.join(", ") }) : t("data.exportError")
179
+ );
177
180
  onExportError?.(error);
178
181
  } finally {
179
182
  setIsExporting(false);
@@ -36,6 +36,7 @@ import { isMessageRef, msg } from "../i18n/msg.js";
36
36
  import { usesCount } from "../i18n/uses-count.js";
37
37
  import { SkeletonTable } from "../components/skeletons/SkeletonTable.js";
38
38
  import { useTableSorting, useDataTableActions } from "../stores/datatable-store.js";
39
+ import { resolveSortColumnId } from "./datatable/sort-field.js";
39
40
  import { jsx, jsxs } from "react/jsx-runtime";
40
41
  function InfiniteList({
41
42
  columns,
@@ -103,8 +104,11 @@ function InfiniteList({
103
104
  const storeSorting = useTableSorting(tableId ?? "");
104
105
  const { setSorting: setStoreSorting } = useDataTableActions(tableId ?? "");
105
106
  const sorting = useMemo(
106
- () => storeSorting.map((s) => ({ id: s.field, desc: s.order === "desc" })),
107
- [storeSorting]
107
+ () => storeSorting.map((s) => ({
108
+ id: resolveSortColumnId(s.field, columns),
109
+ desc: s.order === "desc"
110
+ })),
111
+ [storeSorting, columns]
108
112
  );
109
113
  const handleSortingChange = useCallback(
110
114
  (updater) => {
@@ -0,0 +1,14 @@
1
+ import type { SortField } from '../../types/pagination';
2
+ /**
3
+ * The TanStack column id a stored sort field points at. Accepts both forms:
4
+ * the column id (`customer_name`, what a header click stores) and the data
5
+ * path (`customer.name`, from `defaultSortBy`, a saved view or a `'path'` wire).
6
+ * Unknown fields come back as-is.
7
+ */
8
+ export declare function resolveSortColumnId(field: string, columns: readonly unknown[]): string;
9
+ /**
10
+ * The stored sort as the list sends it to `query.queryFn` (`list.sortParam`).
11
+ * `'id'` (default) sends the stored field unchanged; `'path'` sends the
12
+ * column's `accessorKey` (dots kept), or its id when it has no accessorKey.
13
+ */
14
+ export declare function toSortParam(sorting: SortField[], columns: readonly unknown[], mode?: 'id' | 'path'): SortField[];
@@ -0,0 +1,24 @@
1
+ // src/data/datatable/sort-field.ts
2
+ var accessorKeyOf = (column) => typeof column.accessorKey === "string" ? column.accessorKey : void 0;
3
+ var columnIdOf = (column) => column.id ?? accessorKeyOf(column)?.replace(/\./g, "_");
4
+ function findColumn(field, columns) {
5
+ return columns.find(
6
+ (column) => columnIdOf(column) === field || accessorKeyOf(column) === field
7
+ );
8
+ }
9
+ function resolveSortColumnId(field, columns) {
10
+ const column = findColumn(field, columns);
11
+ return (column && columnIdOf(column)) ?? field;
12
+ }
13
+ function toSortParam(sorting, columns, mode = "id") {
14
+ if (mode !== "path") return sorting;
15
+ return sorting.map((sort) => {
16
+ const column = findColumn(sort.field, columns);
17
+ const path = column && (accessorKeyOf(column) ?? columnIdOf(column));
18
+ return path && path !== sort.field ? { ...sort, field: path } : sort;
19
+ });
20
+ }
21
+ export {
22
+ resolveSortColumnId,
23
+ toSortParam
24
+ };
@@ -25,6 +25,7 @@ import {
25
25
  useTableShowFilters
26
26
  } from "../../stores/datatable-store.js";
27
27
  import { useResponsiveViewMode } from "../../hooks/useResponsiveViewMode.js";
28
+ import { resolveSortColumnId } from "./sort-field.js";
28
29
  function useDataTableInstance({
29
30
  tableId,
30
31
  data,
@@ -74,10 +75,10 @@ function useDataTableInstance({
74
75
  }, [storeColumnFilters]);
75
76
  const sorting = useMemo(() => {
76
77
  return storeSorting.map((s) => ({
77
- id: s.field,
78
+ id: resolveSortColumnId(s.field, columns),
78
79
  desc: s.order === "desc"
79
80
  }));
80
- }, [storeSorting]);
81
+ }, [storeSorting, columns]);
81
82
  const responsiveMode = useResponsiveViewMode(defaultViewMode);
82
83
  useEffect(() => {
83
84
  setCurrentViewMode(responsiveMode);
@@ -41,15 +41,17 @@ export interface PDFExportOptions extends ExportOptions {
41
41
  * Export data to Excel format (.xlsx)
42
42
  *
43
43
  * Features:
44
- * - Preserves column types (numbers, dates)
45
- * - Bold header row
46
- * - Auto-sized columns
47
- * - UTF-8 encoding
44
+ * - Keeps numbers as numeric cells
45
+ * - Bold, shaded header row
46
+ * - Auto-sized columns (10–50 characters)
47
+ * - No dependency: the workbook is written in-house (see `xlsx-writer`)
48
+ *
49
+ * Resolves once the download has been triggered.
48
50
  *
49
51
  * @example
50
- * exportToExcel(data, columns, 'clientes', { t, locale, sheetName: 'Clientes 2025' })
52
+ * await exportToExcel(data, columns, 'clientes', { t, locale, sheetName: 'Clientes 2025' })
51
53
  */
52
- export declare function exportToExcel<T>(data: T[], columns: ColumnDef<T>[], filename: string | undefined, options: ExportOptions): void;
54
+ export declare function exportToExcel<T>(data: T[], columns: ColumnDef<T>[], filename: string | undefined, options: ExportOptions): Promise<void>;
53
55
  /**
54
56
  * Export data to CSV format with UTF-8 BOM (Excel compatibility)
55
57
  *
@@ -65,6 +67,9 @@ export declare function exportToCSV<T>(data: T[], columns: ColumnDef<T>[], filen
65
67
  /**
66
68
  * Export data to PDF format
67
69
  *
70
+ * Needs the optional peers `jspdf` and `jspdf-autotable`, loaded on first use;
71
+ * without them it rejects with an error naming both packages.
72
+ *
68
73
  * Features:
69
74
  * - Landscape or portrait orientation
70
75
  * - Auto page breaks
@@ -73,7 +78,7 @@ export declare function exportToCSV<T>(data: T[], columns: ColumnDef<T>[], filen
73
78
  * - Optional logo and title
74
79
  *
75
80
  * @example
76
- * exportToPDF(data, columns, 'customers', {
81
+ * await exportToPDF(data, columns, 'customers', {
77
82
  * t,
78
83
  * locale,
79
84
  * orientation: 'landscape',
@@ -82,9 +87,9 @@ export declare function exportToCSV<T>(data: T[], columns: ColumnDef<T>[], filen
82
87
  * subtitle: 'January 2025'
83
88
  * })
84
89
  */
85
- export declare function exportToPDF<T>(data: T[], columns: ColumnDef<T>[], filename: string | undefined, options: PDFExportOptions): void;
90
+ export declare function exportToPDF<T>(data: T[], columns: ColumnDef<T>[], filename: string | undefined, options: PDFExportOptions): Promise<void>;
86
91
  /**
87
92
  * Detect and export based on current table state
88
93
  * Helper function that respects filters and sorting
89
94
  */
90
- export declare function exportTableData<T>(data: T[], columns: ColumnDef<T>[], format: 'excel' | 'csv' | 'pdf', filename: string | undefined, options: ExportOptions | PDFExportOptions): void;
95
+ export declare function exportTableData<T>(data: T[], columns: ColumnDef<T>[], format: 'excel' | 'csv' | 'pdf', filename: string | undefined, options: ExportOptions | PDFExportOptions): Promise<void>;
@@ -1,17 +1,41 @@
1
1
  // src/data/exportUtils.ts
2
- import * as XLSX from "xlsx";
3
- import Papa from "papaparse";
4
- import { jsPDF } from "jspdf";
5
- import autoTable from "jspdf-autotable";
6
2
  import { logger } from "../utils/logger.js";
7
3
  import { getColumnLabel } from "./column-label.js";
8
- var unparseCsv = Papa.unparse;
4
+ import { writeXlsx } from "./xlsx-writer.js";
5
+ import { MissingPeerError, isModuleNotFound } from "./missing-peer.js";
9
6
  function buildFilename(name, ext, appendDate = true) {
10
7
  const dated = appendDate && !/\d{4}-\d{2}-\d{2}$/.test(name);
11
8
  const d = /* @__PURE__ */ new Date();
12
9
  const date = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
13
10
  return `${dated ? `${name}_${date}` : name}.${ext}`;
14
11
  }
12
+ function downloadBlob(blob, filename) {
13
+ const url = URL.createObjectURL(blob);
14
+ const link = document.createElement("a");
15
+ link.setAttribute("href", url);
16
+ link.setAttribute("download", filename);
17
+ link.style.visibility = "hidden";
18
+ document.body.appendChild(link);
19
+ link.click();
20
+ document.body.removeChild(link);
21
+ setTimeout(() => URL.revokeObjectURL(url));
22
+ }
23
+ function csvField(value) {
24
+ const text = String(value);
25
+ return /[",\r\n\uFEFF]|^ | $/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
26
+ }
27
+ async function loadPdfPeers() {
28
+ try {
29
+ const [{ jsPDF }, { default: autoTable }] = await Promise.all([
30
+ import("jspdf"),
31
+ import("jspdf-autotable")
32
+ ]);
33
+ return { jsPDF, autoTable };
34
+ } catch (error) {
35
+ if (!isModuleNotFound(error)) throw error;
36
+ throw new MissingPeerError(["jspdf", "jspdf-autotable"], { cause: error });
37
+ }
38
+ }
15
39
  function getColumnHeader(column) {
16
40
  return getColumnLabel(column) ?? column.id ?? "Column";
17
41
  }
@@ -62,70 +86,48 @@ function getExportableColumns(columns, includeHiddenColumns = false) {
62
86
  return true;
63
87
  });
64
88
  }
65
- function exportToExcel(data, columns, filename = "export", options) {
89
+ async function exportToExcel(data, columns, filename = "export", options) {
66
90
  const { includeHiddenColumns = false, sheetName, appendDate, t, locale } = options;
67
91
  const exportColumns = getExportableColumns(columns, includeHiddenColumns);
68
92
  const headers = exportColumns.map((col) => getColumnHeader(col));
69
93
  const rows = data.map(
70
94
  (row) => exportColumns.map((col) => formatValueForExport(getCellValue(row, col), t, locale))
71
95
  );
72
- const ws = XLSX.utils.aoa_to_sheet([headers, ...rows]);
73
- const colWidths = exportColumns.map((_col, idx) => {
74
- const headerLength = headers[idx].length;
96
+ const widths = headers.map((header, idx) => {
75
97
  const maxDataLength = Math.max(
76
98
  ...rows.map((row) => String(row[idx] || "").length),
77
99
  10
78
100
  // Minimum width
79
101
  );
80
- return { wch: Math.min(Math.max(headerLength, maxDataLength), 50) };
102
+ return Math.min(Math.max(header.length, maxDataLength), 50);
81
103
  });
82
- ws["!cols"] = colWidths;
83
- const range = XLSX.utils.decode_range(ws["!ref"] || "A1");
84
- for (let col = range.s.c; col <= range.e.c; col++) {
85
- const cellAddress = XLSX.utils.encode_cell({ r: 0, c: col });
86
- if (!ws[cellAddress]) continue;
87
- ws[cellAddress].s = {
88
- font: { bold: true },
89
- fill: { fgColor: { rgb: "F3F4F6" } }
90
- };
91
- }
92
- const wb = XLSX.utils.book_new();
93
- XLSX.utils.book_append_sheet(wb, ws, sheetName ?? t("data.sheetName"));
94
- XLSX.writeFile(wb, buildFilename(filename, "xlsx", appendDate));
104
+ const bytes = await writeXlsx({
105
+ name: sheetName ?? t("data.sheetName"),
106
+ headers,
107
+ rows,
108
+ widths
109
+ });
110
+ downloadBlob(
111
+ new Blob([bytes], {
112
+ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
113
+ }),
114
+ buildFilename(filename, "xlsx", appendDate)
115
+ );
95
116
  }
96
117
  function exportToCSV(data, columns, filename = "export", options) {
97
118
  const { includeHiddenColumns = false, appendDate, t, locale } = options;
98
119
  const exportColumns = getExportableColumns(columns, includeHiddenColumns);
99
120
  const headers = exportColumns.map((col) => getColumnHeader(col));
100
121
  const rows = data.map(
101
- (row) => exportColumns.reduce(
102
- (acc, col) => {
103
- const header = getColumnHeader(col);
104
- acc[header] = formatValueForExport(getCellValue(row, col), t, locale);
105
- return acc;
106
- },
107
- {}
108
- )
122
+ (row) => exportColumns.map((col) => formatValueForExport(getCellValue(row, col), t, locale))
123
+ );
124
+ const csv = [headers, ...rows].map((r) => r.map(csvField).join(",")).join("\r\n");
125
+ downloadBlob(
126
+ new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8;" }),
127
+ buildFilename(filename, "csv", appendDate)
109
128
  );
110
- const csv = unparseCsv(rows, {
111
- columns: headers,
112
- delimiter: ",",
113
- header: true,
114
- skipEmptyLines: true
115
- });
116
- const BOM = "\uFEFF";
117
- const csvWithBOM = BOM + csv;
118
- const blob = new Blob([csvWithBOM], { type: "text/csv;charset=utf-8;" });
119
- const link = document.createElement("a");
120
- const url = URL.createObjectURL(blob);
121
- link.setAttribute("href", url);
122
- link.setAttribute("download", buildFilename(filename, "csv", appendDate));
123
- link.style.visibility = "hidden";
124
- document.body.appendChild(link);
125
- link.click();
126
- document.body.removeChild(link);
127
129
  }
128
- function exportToPDF(data, columns, filename = "export", options) {
130
+ async function exportToPDF(data, columns, filename = "export", options) {
129
131
  const {
130
132
  includeHiddenColumns = false,
131
133
  orientation = "landscape",
@@ -138,6 +140,7 @@ function exportToPDF(data, columns, filename = "export", options) {
138
140
  t,
139
141
  locale
140
142
  } = options;
143
+ const { jsPDF, autoTable } = await loadPdfPeers();
141
144
  const exportColumns = getExportableColumns(columns, includeHiddenColumns);
142
145
  const doc = new jsPDF({
143
146
  orientation,
@@ -236,17 +239,14 @@ function exportToPDF(data, columns, filename = "export", options) {
236
239
  });
237
240
  doc.save(buildFilename(filename, "pdf", appendDate));
238
241
  }
239
- function exportTableData(data, columns, format, filename = "export", options) {
242
+ async function exportTableData(data, columns, format, filename = "export", options) {
240
243
  switch (format) {
241
244
  case "excel":
242
- exportToExcel(data, columns, filename, options);
243
- break;
245
+ return exportToExcel(data, columns, filename, options);
244
246
  case "csv":
245
- exportToCSV(data, columns, filename, options);
246
- break;
247
+ return exportToCSV(data, columns, filename, options);
247
248
  case "pdf":
248
- exportToPDF(data, columns, filename, options);
249
- break;
249
+ return exportToPDF(data, columns, filename, options);
250
250
  default:
251
251
  logger.error(`Unknown export format: ${format}`);
252
252
  }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Thrown when a feature needs an optional peer dependency the app did not
3
+ * install (e.g. PDF export → `jspdf` + `jspdf-autotable`). Callers turn it
4
+ * into a localized message naming `packages`.
5
+ */
6
+ export declare class MissingPeerError extends Error {
7
+ readonly packages: string[];
8
+ readonly name = "MissingPeerError";
9
+ constructor(packages: string[], options?: {
10
+ cause?: unknown;
11
+ });
12
+ }
13
+ /**
14
+ * Whether `error` is a module-not-found failure (webpack/Turbopack, Node, Vite),
15
+ * as opposed to a network/chunk error that should surface unchanged.
16
+ */
17
+ export declare function isModuleNotFound(error: unknown): boolean;
@@ -0,0 +1,22 @@
1
+ // src/data/missing-peer.ts
2
+ var MissingPeerError = class extends Error {
3
+ constructor(packages, options) {
4
+ const list = packages.join(" ");
5
+ super(`Missing optional peer dependency: install ${list} (pnpm add ${list})`, options);
6
+ this.packages = packages;
7
+ }
8
+ packages;
9
+ name = "MissingPeerError";
10
+ };
11
+ function isModuleNotFound(error) {
12
+ for (let e = error; e instanceof Error; e = e.cause) {
13
+ const code = e.code;
14
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") return true;
15
+ if (/Cannot find (module|package)|Failed to resolve/.test(e.message)) return true;
16
+ }
17
+ return false;
18
+ }
19
+ export {
20
+ MissingPeerError,
21
+ isModuleNotFound
22
+ };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Minimal XLSX writer: one worksheet, inline strings and numbers, a bold
3
+ * shaded header row and column widths — everything `exportToExcel` needs.
4
+ *
5
+ * Replaces the `xlsx` (SheetJS) peer: npm only carries SheetJS 0.18.5, flagged
6
+ * by CVE-2023-30533 and CVE-2024-22363, and the fixed builds live outside the
7
+ * registry. Writing the OOXML parts ourselves costs no dependency at all; the
8
+ * zip is compressed with the platform's `CompressionStream` and falls back to
9
+ * stored entries where that API is missing.
10
+ */
11
+ export type XlsxCell = string | number | boolean;
12
+ export interface XlsxSheet {
13
+ /** Sanitized to Excel's rules (31 chars, no `\ / ? * [ ] :`). */
14
+ name: string;
15
+ /** Rendered bold on a light gray fill. */
16
+ headers: string[];
17
+ rows: XlsxCell[][];
18
+ /** Column widths in characters, by column index. */
19
+ widths?: number[];
20
+ }
21
+ /** Excel sheet-name rules; `Sheet1` when nothing usable is left. */
22
+ export declare function sanitizeSheetName(name: string): string;
23
+ /** The bytes of a single-sheet `.xlsx` workbook. */
24
+ export declare function writeXlsx(sheet: XlsxSheet): Promise<Uint8Array<ArrayBuffer>>;