@undevy-org/tablewright 0.7.10 → 0.8.1

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.
@@ -0,0 +1,48 @@
1
+ import { jsxs, jsx } from "react/jsx-runtime";
2
+ import { FileDown } from "lucide-react";
3
+ import { resolveCsvExportLabel, resolveExportColumnsFromTable, exportTableToCsv, downloadCsvFile, resolveTableExportButtonSize, resolveTableExportButtonVariant, defaultTableRowCellText } from "../../lib/export-table-csv.js";
4
+ import { cn } from "../../lib/utils.js";
5
+ import { Button } from "../ui/button.js";
6
+ function TableCsvExportButton({
7
+ table,
8
+ filename,
9
+ getCellText,
10
+ utf8Bom,
11
+ columnIds,
12
+ labels,
13
+ className,
14
+ variant,
15
+ size
16
+ }) {
17
+ const buttonVariant = resolveTableExportButtonVariant(variant);
18
+ const buttonSize = resolveTableExportButtonSize(size);
19
+ const exportLabel = resolveCsvExportLabel(labels);
20
+ const handleExport = () => {
21
+ const columns = resolveExportColumnsFromTable(table, columnIds, labels?.columns);
22
+ const rows = table.getRowModel().rows.map((row) => row.original);
23
+ const resolveCellText = getCellText ?? ((row, columnId) => defaultTableRowCellText(row, columnId, table));
24
+ const csv = exportTableToCsv({
25
+ columns,
26
+ rows,
27
+ getCellText: resolveCellText
28
+ });
29
+ downloadCsvFile(csv, filename, { utf8Bom });
30
+ };
31
+ return /* @__PURE__ */ jsxs(
32
+ Button,
33
+ {
34
+ type: "button",
35
+ variant: buttonVariant,
36
+ size: buttonSize,
37
+ className: cn("shrink-0", className),
38
+ onClick: handleExport,
39
+ children: [
40
+ /* @__PURE__ */ jsx(FileDown, { className: "h-4 w-4" }),
41
+ exportLabel
42
+ ]
43
+ }
44
+ );
45
+ }
46
+ export {
47
+ TableCsvExportButton
48
+ };
package/dist/es/index.js CHANGED
@@ -32,6 +32,7 @@ import { RowActionsMenu } from "./components/data-table/RowActionsMenu.js";
32
32
  import { RowControlCell, RowControlHeader } from "./components/data-table/RowControlCell.js";
33
33
  import { SortableHeader } from "./components/data-table/SortableHeader.js";
34
34
  import { TableFooter } from "./components/data-table/TableFooter.js";
35
+ import { TableCsvExportButton } from "./components/data-table/TableCsvExportButton.js";
35
36
  import { TableLayout } from "./components/data-table/TableLayout.js";
36
37
  import { useColumnResize } from "./components/data-table/hooks/use-column-resize.js";
37
38
  import { getVisiblePageNumbers } from "./components/data-table/hooks/use-table-pagination.js";
@@ -65,6 +66,7 @@ import { getCompoundValue, getDateRange, getNumberRange, getStringArray, isFilte
65
66
  import { useTableOrchestration } from "./hooks/useTableOrchestration.js";
66
67
  import { createTableOrchestrationStore, defaultValueForFilter } from "./hooks/table-orchestration-store.js";
67
68
  import { useRowDragOverride } from "./hooks/useRowDragOverride.js";
69
+ import { downloadCsvFile, exportTableToCsv } from "./lib/export-table-csv.js";
68
70
  import { computeColumnGaps, gapColumnId } from "./lib/column-gaps.js";
69
71
  import { computeColumnStats } from "./lib/filter-stats.js";
70
72
  import { formatEnumLabel } from "./lib/format-enum.js";
@@ -162,6 +164,7 @@ export {
162
164
  SidebarAccountMenu,
163
165
  SidebarUser,
164
166
  SortableHeader,
167
+ TableCsvExportButton,
165
168
  TableFooter,
166
169
  TableLayout,
167
170
  Tabs,
@@ -183,6 +186,8 @@ export {
183
186
  createTableOrchestrationStore,
184
187
  defaultValueForFilter,
185
188
  displayTimeZone,
189
+ downloadCsvFile,
190
+ exportTableToCsv,
186
191
  formatDateParts,
187
192
  formatEnumLabel,
188
193
  formatLiveTimestamp,
@@ -0,0 +1,104 @@
1
+ const DEFAULT_CSV_EXPORT_LABEL = "Export CSV";
2
+ function resolveCsvExportLabel(labels) {
3
+ return labels?.export ?? DEFAULT_CSV_EXPORT_LABEL;
4
+ }
5
+ function resolveTableExportButtonSize(size) {
6
+ return size ?? "default";
7
+ }
8
+ function resolveTableExportButtonVariant(variant) {
9
+ return variant ?? "secondary";
10
+ }
11
+ const PLAIN_DECIMAL_CORE = /^(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/;
12
+ const FORMULA_TRIGGER_PREFIX = /^[=+\-@\t\r]/;
13
+ function escapeCsvField(value) {
14
+ if (/[",\r\n]/.test(value)) {
15
+ return `"${value.replace(/"/g, '""')}"`;
16
+ }
17
+ return value;
18
+ }
19
+ function isSignedPlainDecimal(value) {
20
+ const first = value[0];
21
+ if (first !== "+" && first !== "-") {
22
+ return false;
23
+ }
24
+ return PLAIN_DECIMAL_CORE.test(value.slice(1));
25
+ }
26
+ function shouldPrefixFormulaEscape(value) {
27
+ if (!FORMULA_TRIGGER_PREFIX.test(value)) {
28
+ return false;
29
+ }
30
+ if (isSignedPlainDecimal(value)) {
31
+ return false;
32
+ }
33
+ return true;
34
+ }
35
+ function formatCsvField(value, escapeFormulas) {
36
+ const prepared = escapeFormulas && shouldPrefixFormulaEscape(value) ? `'${value}` : value;
37
+ return escapeCsvField(prepared);
38
+ }
39
+ function exportTableToCsv(options) {
40
+ const { columns, rows, getCellText, escapeFormulas = true } = options;
41
+ const headerLine = columns.map((column) => formatCsvField(column.header, escapeFormulas)).join(",");
42
+ const bodyLines = rows.map(
43
+ (row) => columns.map((column) => formatCsvField(getCellText(row, column.id), escapeFormulas)).join(",")
44
+ );
45
+ return [headerLine, ...bodyLines].join("\r\n");
46
+ }
47
+ function downloadCsvFile(content, filename, options) {
48
+ const utf8Bom = options?.utf8Bom ?? false;
49
+ const payload = utf8Bom ? `\uFEFF${content}` : content;
50
+ const blob = new Blob([payload], { type: "text/csv;charset=utf-8" });
51
+ const url = URL.createObjectURL(blob);
52
+ const anchor = document.createElement("a");
53
+ anchor.href = url;
54
+ anchor.download = filename.endsWith(".csv") ? filename : `${filename}.csv`;
55
+ anchor.rel = "noopener";
56
+ anchor.style.display = "none";
57
+ document.body.appendChild(anchor);
58
+ anchor.click();
59
+ document.body.removeChild(anchor);
60
+ URL.revokeObjectURL(url);
61
+ }
62
+ function resolveColumnHeader(table, columnId, columnLabels) {
63
+ if (columnLabels?.[columnId]) {
64
+ return columnLabels[columnId];
65
+ }
66
+ const column = table.getColumn(columnId);
67
+ if (!column) {
68
+ return columnId;
69
+ }
70
+ const header = column.columnDef.header;
71
+ return typeof header === "string" ? header : columnId;
72
+ }
73
+ function resolveExportColumnsFromTable(table, columnIds, columnLabels) {
74
+ const ids = columnIds ?? table.getVisibleLeafColumns().map((column) => column.id);
75
+ return ids.map((id) => ({
76
+ id,
77
+ header: resolveColumnHeader(table, id, columnLabels)
78
+ }));
79
+ }
80
+ function defaultTableRowCellText(row, columnId, table) {
81
+ const tableRow = table.getRowModel().rows.find((candidate) => candidate.original === row);
82
+ if (!tableRow) {
83
+ return "";
84
+ }
85
+ const cell = tableRow.getAllCells().find((candidate) => candidate.column.id === columnId);
86
+ if (!cell) {
87
+ return "";
88
+ }
89
+ const value = cell.getValue();
90
+ if (value == null) {
91
+ return "";
92
+ }
93
+ return String(value);
94
+ }
95
+ export {
96
+ DEFAULT_CSV_EXPORT_LABEL,
97
+ defaultTableRowCellText,
98
+ downloadCsvFile,
99
+ exportTableToCsv,
100
+ resolveCsvExportLabel,
101
+ resolveExportColumnsFromTable,
102
+ resolveTableExportButtonSize,
103
+ resolveTableExportButtonVariant
104
+ };
@@ -1814,6 +1814,140 @@ function renderNumericPager(props) {
1814
1814
  )
1815
1815
  ] });
1816
1816
  }
1817
+ const DEFAULT_CSV_EXPORT_LABEL = "Export CSV";
1818
+ function resolveCsvExportLabel(labels) {
1819
+ return labels?.export ?? DEFAULT_CSV_EXPORT_LABEL;
1820
+ }
1821
+ function resolveTableExportButtonSize(size) {
1822
+ return size ?? "default";
1823
+ }
1824
+ function resolveTableExportButtonVariant(variant) {
1825
+ return variant ?? "secondary";
1826
+ }
1827
+ const PLAIN_DECIMAL_CORE = /^(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/;
1828
+ const FORMULA_TRIGGER_PREFIX = /^[=+\-@\t\r]/;
1829
+ function escapeCsvField(value) {
1830
+ if (/[",\r\n]/.test(value)) {
1831
+ return `"${value.replace(/"/g, '""')}"`;
1832
+ }
1833
+ return value;
1834
+ }
1835
+ function isSignedPlainDecimal(value) {
1836
+ const first = value[0];
1837
+ if (first !== "+" && first !== "-") {
1838
+ return false;
1839
+ }
1840
+ return PLAIN_DECIMAL_CORE.test(value.slice(1));
1841
+ }
1842
+ function shouldPrefixFormulaEscape(value) {
1843
+ if (!FORMULA_TRIGGER_PREFIX.test(value)) {
1844
+ return false;
1845
+ }
1846
+ if (isSignedPlainDecimal(value)) {
1847
+ return false;
1848
+ }
1849
+ return true;
1850
+ }
1851
+ function formatCsvField(value, escapeFormulas) {
1852
+ const prepared = escapeFormulas && shouldPrefixFormulaEscape(value) ? `'${value}` : value;
1853
+ return escapeCsvField(prepared);
1854
+ }
1855
+ function exportTableToCsv(options) {
1856
+ const { columns, rows, getCellText, escapeFormulas = true } = options;
1857
+ const headerLine = columns.map((column) => formatCsvField(column.header, escapeFormulas)).join(",");
1858
+ const bodyLines = rows.map(
1859
+ (row) => columns.map((column) => formatCsvField(getCellText(row, column.id), escapeFormulas)).join(",")
1860
+ );
1861
+ return [headerLine, ...bodyLines].join("\r\n");
1862
+ }
1863
+ function downloadCsvFile(content, filename, options) {
1864
+ const utf8Bom = options?.utf8Bom ?? false;
1865
+ const payload = utf8Bom ? `\uFEFF${content}` : content;
1866
+ const blob = new Blob([payload], { type: "text/csv;charset=utf-8" });
1867
+ const url = URL.createObjectURL(blob);
1868
+ const anchor = document.createElement("a");
1869
+ anchor.href = url;
1870
+ anchor.download = filename.endsWith(".csv") ? filename : `${filename}.csv`;
1871
+ anchor.rel = "noopener";
1872
+ anchor.style.display = "none";
1873
+ document.body.appendChild(anchor);
1874
+ anchor.click();
1875
+ document.body.removeChild(anchor);
1876
+ URL.revokeObjectURL(url);
1877
+ }
1878
+ function resolveColumnHeader(table, columnId, columnLabels) {
1879
+ if (columnLabels?.[columnId]) {
1880
+ return columnLabels[columnId];
1881
+ }
1882
+ const column = table.getColumn(columnId);
1883
+ if (!column) {
1884
+ return columnId;
1885
+ }
1886
+ const header = column.columnDef.header;
1887
+ return typeof header === "string" ? header : columnId;
1888
+ }
1889
+ function resolveExportColumnsFromTable(table, columnIds, columnLabels) {
1890
+ const ids = columnIds ?? table.getVisibleLeafColumns().map((column) => column.id);
1891
+ return ids.map((id) => ({
1892
+ id,
1893
+ header: resolveColumnHeader(table, id, columnLabels)
1894
+ }));
1895
+ }
1896
+ function defaultTableRowCellText(row, columnId, table) {
1897
+ const tableRow = table.getRowModel().rows.find((candidate) => candidate.original === row);
1898
+ if (!tableRow) {
1899
+ return "";
1900
+ }
1901
+ const cell = tableRow.getAllCells().find((candidate) => candidate.column.id === columnId);
1902
+ if (!cell) {
1903
+ return "";
1904
+ }
1905
+ const value = cell.getValue();
1906
+ if (value == null) {
1907
+ return "";
1908
+ }
1909
+ return String(value);
1910
+ }
1911
+ function TableCsvExportButton({
1912
+ table,
1913
+ filename,
1914
+ getCellText,
1915
+ utf8Bom,
1916
+ columnIds,
1917
+ labels,
1918
+ className,
1919
+ variant,
1920
+ size
1921
+ }) {
1922
+ const buttonVariant = resolveTableExportButtonVariant(variant);
1923
+ const buttonSize = resolveTableExportButtonSize(size);
1924
+ const exportLabel = resolveCsvExportLabel(labels);
1925
+ const handleExport = () => {
1926
+ const columns = resolveExportColumnsFromTable(table, columnIds, labels?.columns);
1927
+ const rows = table.getRowModel().rows.map((row) => row.original);
1928
+ const resolveCellText = getCellText ?? ((row, columnId) => defaultTableRowCellText(row, columnId, table));
1929
+ const csv = exportTableToCsv({
1930
+ columns,
1931
+ rows,
1932
+ getCellText: resolveCellText
1933
+ });
1934
+ downloadCsvFile(csv, filename, { utf8Bom });
1935
+ };
1936
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1937
+ Button,
1938
+ {
1939
+ type: "button",
1940
+ variant: buttonVariant,
1941
+ size: buttonSize,
1942
+ className: cn("shrink-0", className),
1943
+ onClick: handleExport,
1944
+ children: [
1945
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileDown, { className: "h-4 w-4" }),
1946
+ exportLabel
1947
+ ]
1948
+ }
1949
+ );
1950
+ }
1817
1951
  function useColumnResize(defaults, initialWidths) {
1818
1952
  const [widths, setWidths] = React.useState(() => {
1819
1953
  const w = {};
@@ -5943,6 +6077,7 @@ exports.Sidebar = Sidebar;
5943
6077
  exports.SidebarAccountMenu = SidebarAccountMenu;
5944
6078
  exports.SidebarUser = SidebarUser;
5945
6079
  exports.SortableHeader = SortableHeader;
6080
+ exports.TableCsvExportButton = TableCsvExportButton;
5946
6081
  exports.TableFooter = TableFooter;
5947
6082
  exports.TableLayout = TableLayout;
5948
6083
  exports.Tabs = Tabs;
@@ -5964,6 +6099,8 @@ exports.computeColumnStats = computeColumnStats;
5964
6099
  exports.createTableOrchestrationStore = createTableOrchestrationStore;
5965
6100
  exports.defaultValueForFilter = defaultValueForFilter;
5966
6101
  exports.displayTimeZone = displayTimeZone;
6102
+ exports.downloadCsvFile = downloadCsvFile;
6103
+ exports.exportTableToCsv = exportTableToCsv;
5967
6104
  exports.formatDateParts = formatDateParts;
5968
6105
  exports.formatEnumLabel = formatEnumLabel;
5969
6106
  exports.formatLiveTimestamp = formatLiveTimestamp;
@@ -0,0 +1,20 @@
1
+ import type { Table } from "@tanstack/react-table";
2
+ import { type ButtonProps } from "../ui/button.js";
3
+ export type TableCsvExportButtonLabels = {
4
+ /** @default "Export CSV" */
5
+ export?: string;
6
+ columns?: Record<string, string>;
7
+ };
8
+ export type TableCsvExportButtonProps<TData> = {
9
+ table: Table<TData>;
10
+ filename: string;
11
+ getCellText?: (row: TData, columnId: string) => string;
12
+ utf8Bom?: boolean;
13
+ /** Defaults to visible leaf columns on the table instance. */
14
+ columnIds?: string[];
15
+ labels?: TableCsvExportButtonLabels;
16
+ className?: string;
17
+ variant?: ButtonProps["variant"];
18
+ size?: ButtonProps["size"];
19
+ };
20
+ export declare function TableCsvExportButton<TData>({ table, filename, getCellText, utf8Bom, columnIds, labels, className, variant, size, }: TableCsvExportButtonProps<TData>): import("react").JSX.Element;
@@ -46,6 +46,8 @@ export { RowControlHeader } from "./components/data-table/RowControlCell.js";
46
46
  export type { RowControlHeaderProps } from "./components/data-table/RowControlCell.js";
47
47
  export { SortableHeader } from "./components/data-table/SortableHeader.js";
48
48
  export { TableFooter } from "./components/data-table/TableFooter.js";
49
+ export { TableCsvExportButton } from "./components/data-table/TableCsvExportButton.js";
50
+ export type { TableCsvExportButtonProps } from "./components/data-table/TableCsvExportButton.js";
49
51
  export { TableLayout } from "./components/data-table/TableLayout.js";
50
52
  export { useColumnResize } from "./components/data-table/hooks/use-column-resize.js";
51
53
  export { getVisiblePageNumbers } from "./components/data-table/hooks/use-table-pagination.js";
@@ -100,6 +102,8 @@ export { createTableOrchestrationStore, defaultValueForFilter, } from "./hooks/t
100
102
  export type { TableOrchestrationState, TableOrchestrationActions, TableOrchestrationStore, TableOrchestrationStoreApi, } from "./hooks/table-orchestration-store.js";
101
103
  export { useRowDragOverride } from "./hooks/useRowDragOverride.js";
102
104
  export type { UseRowDragOverrideResult } from "./hooks/useRowDragOverride.js";
105
+ export { downloadCsvFile, exportTableToCsv, } from "./lib/export-table-csv.js";
106
+ export type { DownloadCsvFileOptions, ExportTableToCsvOptions, } from "./lib/export-table-csv.js";
103
107
  export { computeColumnGaps, gapColumnId } from "./lib/column-gaps.js";
104
108
  export { computeColumnStats } from "./lib/filter-stats.js";
105
109
  export { formatEnumLabel } from "./lib/format-enum.js";
@@ -0,0 +1,31 @@
1
+ import type { Table } from "@tanstack/react-table";
2
+ export type ExportTableToCsvOptions<TRow> = {
3
+ columns: {
4
+ id: string;
5
+ header: string;
6
+ }[];
7
+ rows: TRow[];
8
+ getCellText: (row: TRow, columnId: string) => string;
9
+ /**
10
+ * Prefix formula-triggering cell text with `'` so spreadsheet apps do not evaluate it.
11
+ * Plain decimal numbers (`-5`, `+3.2`) are left unchanged. @default true
12
+ */
13
+ escapeFormulas?: boolean;
14
+ };
15
+ export declare const DEFAULT_CSV_EXPORT_LABEL = "Export CSV";
16
+ export declare function resolveCsvExportLabel(labels?: {
17
+ export?: string;
18
+ }): string;
19
+ export declare function resolveTableExportButtonSize<TSize extends string | null | undefined>(size: TSize): NonNullable<TSize> | "default";
20
+ export declare function resolveTableExportButtonVariant<TVariant extends string | null | undefined>(variant: TVariant): NonNullable<TVariant> | "secondary";
21
+ export type DownloadCsvFileOptions = {
22
+ /** Prepends a UTF-8 BOM so Excel recognizes UTF-8. @default false */
23
+ utf8Bom?: boolean;
24
+ };
25
+ export declare function exportTableToCsv<TRow>(options: ExportTableToCsvOptions<TRow>): string;
26
+ export declare function downloadCsvFile(content: string, filename: string, options?: DownloadCsvFileOptions): void;
27
+ export declare function resolveExportColumnsFromTable<TData>(table: Table<TData>, columnIds?: string[], columnLabels?: Record<string, string>): {
28
+ id: string;
29
+ header: string;
30
+ }[];
31
+ export declare function defaultTableRowCellText<TData>(row: TData, columnId: string, table: Table<TData>): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@undevy-org/tablewright",
3
- "version": "0.7.10",
3
+ "version": "0.8.1",
4
4
  "description": "React data-table and application-shell components: filters, drawers, row controls, sortable and resizable columns, built on Radix UI and TanStack Table.",
5
5
  "license": "MIT",
6
6
  "repository": {