Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/data-table-export-columns.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@wirecore/wirelayer-recipes': minor
'@wirecore/wirelayer-vue': minor
'@wirecore/wirelayer-react': minor
'@wirecore/wirelayer-native': minor
---

DataTable: `exportColumns` splits a column into several columns of the CSV and Excel export, at its position – e.g.
"Name" shown as "Doe, Jane" exported as "First name" and "Last name". It takes precedence over `exportHeader` and
`exportValue`; `exportable: false` and a hidden column export nothing. In Excel the aggregate and footer of the column go
to its first part. Printing keeps the shown column. The React Native DataTable exports the same way (`tableCsv`,
`tableXlsxSheet`); new recipe helper `tableExportColumns`. Story _Export columns_.
27 changes: 27 additions & 0 deletions apps/storybook/src/Introduction.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,33 @@ narrow screens). `minScrollHeight` keeps it from collapsing; below that the page
</main>
```

## DataTable export (CSV, Excel)

`exportFilename` shows the export button, `exportFormats` picks CSV, Excel (.xlsx) or both; `generateCsv()` and
`generateXlsx()` return the file instead of downloading it. The export has the filtered and sorted rows of all pages (or
the selection) and the visible columns in their current order. Per column: `exportable: false` leaves it out,
`exportHeader` and `exportValue` replace the name and the value, and `exportColumns` splits it into several columns at
its position – the table keeps showing one column, and printing too:

```ts
const columns: DataTableColumn<Person>[] = [
{
id: 'name',
header: 'Name',
accessor: (row) => `${row.lastName}, ${row.firstName}`, // shown: "Doe, Jane"
exportColumns: [
{ header: 'First name', value: (row) => row.firstName },
{ header: 'Last name', value: (row) => row.lastName },
],
},
{ id: 'club', header: 'Club' },
];
// CSV: First name;Last name;Club
```

`exportColumns` takes precedence over `exportHeader` and `exportValue`. In Excel the aggregate and the footer of a split
column go to its first part. The React Native DataTable exports the same way.

## AI assistants (MCP, llms.txt)

So that Claude, Cursor and others use the components correctly, the API is available as text and as an MCP server:
Expand Down
5 changes: 5 additions & 0 deletions packages/mcp/data/components.json
Original file line number Diff line number Diff line change
Expand Up @@ -38146,6 +38146,11 @@
"title": "DataTable feature modules",
"text": "Parts of the DataTable that bring a lot of code along are imported on their own – an app only bundles the ones it passes\nin `features` (fixed for the life of a table). The DatePicker alone is about 40 KB (gzip).\n\n| Feature | Import | Adds | Without it |\n| ---------------- | ---------------------------------------------------------------------- | ---------------------------------------------------- | -------------------------------------------- |\n| `virtualRows` | `@wirecore/wirelayer-react/virtual` (peer dependency TanStack Virtual) | only the visible rows are rendered with `virtual` | all rows are rendered, a hint in development |\n| `dateInput` | `@wirecore/wirelayer-react/data-table` | DatePicker for `date` and `datetime` filters/editors | the browser's date input |\n| `numberInput` | `@wirecore/wirelayer-react/data-table` | NumberInput for `number` filters and editors | the browser's number input |\n| `dateRangeInput` | `@wirecore/wirelayer-react/data-table` | one DateRangePicker for `between` filters of dates | two fields (from, to) |\n\n```tsx\nimport { DataTable, dateInput, numberInput } from '@wirecore/wirelayer-react/data-table';\nimport { virtualRows } from '@wirecore/wirelayer-react/virtual';\n\n// Once for all tables of the app\nconst features = [virtualRows, dateInput, numberInput];\n\n<DataTable data={rows} columns={columns} features={features} scrollHeight=\"480px\" virtual />;\n```\n\n```vue\n<DataTable :data=\"rows\" :columns=\"columns\" :features=\"features\" scroll-height=\"480px\" virtual />\n```\n\nVue: the same imports from `@wirecore/wirelayer-vue/data-table` and `@wirecore/wirelayer-vue/virtual`.\n\n`scrollHeight` takes a CSS length – the maximum height, the rows scroll inside – or `fill`: the table takes the rest of a\nflex column and the rows scroll in the room left down to its bottom, whatever is above it (headings, figures that wrap on\nnarrow screens). `minScrollHeight` keeps it from collapsing; below that the page scrolls.\n\n```vue\n<main class=\"flex min-h-screen flex-col gap-4 p-6\">\n <PageHeader title=\"Machines\" />\n <StatsRow />\n <DataTable :data=\"rows\" :columns=\"columns\" :features=\"features\" scroll-height=\"fill\" min-scroll-height=\"60vh\" virtual />\n</main>\n```"
},
{
"id": "introduction-datatable-export-csv-excel",
"title": "DataTable export (CSV, Excel)",
"text": "`exportFilename` shows the export button, `exportFormats` picks CSV, Excel (.xlsx) or both; `generateCsv()` and\n`generateXlsx()` return the file instead of downloading it. The export has the filtered and sorted rows of all pages (or\nthe selection) and the visible columns in their current order. Per column: `exportable: false` leaves it out,\n`exportHeader` and `exportValue` replace the name and the value, and `exportColumns` splits it into several columns at\nits position – the table keeps showing one column, and printing too:\n\n```ts\nconst columns: DataTableColumn<Person>[] = [\n {\n id: 'name',\n header: 'Name',\n accessor: (row) => `${row.lastName}, ${row.firstName}`, // shown: \"Doe, Jane\"\n exportColumns: [\n { header: 'First name', value: (row) => row.firstName },\n { header: 'Last name', value: (row) => row.lastName },\n ],\n },\n { id: 'club', header: 'Club' },\n];\n// CSV: First name;Last name;Club\n```\n\n`exportColumns` takes precedence over `exportHeader` and `exportValue`. In Excel the aggregate and the footer of a split\ncolumn go to its first part. The React Native DataTable exports the same way."
},
{
"id": "introduction-ai-assistants-mcp-llms-txt",
"title": "AI assistants (MCP, llms.txt)",
Expand Down
6 changes: 6 additions & 0 deletions packages/native/src/data-table/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ export interface DataTableColumn<TData> {
exportHeader?: string;
/** Value in the export (default: the shown text) */
exportValue?: (row: TData) => unknown;
/**
* The column is replaced by these columns in the CSV/Excel export (in this order, at its position) – e.g. "Name"
* shown as "Doe, Jane" exported as "First name" and "Last name". Takes precedence over `exportHeader` and
* `exportValue`; with `exportable: false` nothing is exported
*/
exportColumns?: { header: string; value: (row: TData) => unknown }[];
/** Own cell content (default: the formatted value) – screen readers still read "header: text" on iOS/Android */
cell?: (row: TData, value: unknown) => ReactNode;
}
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
98 changes: 98 additions & 0 deletions packages/parity/src/data-table.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1717,6 +1717,70 @@ describe.each(frameworks)('%s DataTable', (framework) => {
);
});

it('exportColumns: a column becomes several export columns at its position; hidden or not exportable: none', async () => {
let handle: { generateCsv: (options?: object) => string } | undefined;
const kind = (row: { name: string }) => row.name.split('-')[0];
const number = (row: { name: string }) => row.name.split('-').slice(1).join('-');
const split = (hiddenColumns: string[]) =>
table({
ref: (value: typeof handle | null) => (handle = value ?? handle),
hiddenColumns,
columns: [
{
id: 'name',
header: 'Name',
// exportColumns takes precedence
exportHeader: 'Hostname',
exportValue: () => 'unused',
exportColumns: [
{ header: 'Kind', value: kind },
{ header: 'Number', value: number },
],
},
{ id: 'location', header: 'Location' },
{
id: 'load',
header: 'Load',
exportable: false,
exportColumns: [{ header: 'Never', value: () => 1 }],
},
],
});
await render(framework, split([]));
expect(handle!.generateCsv({ bom: false }).split('\r\n')).toEqual([
'Kind,Number,Location',
'web,01,Frankfurt',
'db,primary,Frankfurt',
'k8s,node-3,Nuremberg',
]);
// The table still shows the one column
expect(screen.getByRole('columnheader', { name: 'Name' })).toBeInTheDocument();
expect(screen.queryByRole('columnheader', { name: 'Kind' })).not.toBeInTheDocument();
});

it('exportColumns of a hidden column are left out too', async () => {
let handle: { generateCsv: (options?: object) => string } | undefined;
await render(
framework,
table({
ref: (value: typeof handle | null) => (handle = value ?? handle),
hiddenColumns: ['name'],
columns: [
{
id: 'name',
header: 'Name',
exportColumns: [
{ header: 'Kind', value: () => 'k' },
{ header: 'Number', value: () => 'n' },
],
},
{ id: 'location', header: 'Location' },
],
})
);
expect(handle!.generateCsv({ bom: false }).split('\r\n')[0]).toBe('Location');
});

it('csvSeparator sets the separator of the export, the option of a single export still wins', async () => {
let handle: { generateCsv: (options?: object) => string } | undefined;
await render(
Expand Down Expand Up @@ -2034,6 +2098,40 @@ describe.each(frameworks)('%s DataTable spreadsheet, server and layout', (framew
expect(screen.getByRole('menuitem', { name: 'All rows as CSV' })).toBeInTheDocument();
});

it('Excel export with exportColumns: the parts as columns, aggregates and footer in the first part', async () => {
let handle: Handle | undefined;
await render(
framework,
table({
ref: (value: Handle | null) => (handle = value ?? handle),
columns: [
{ id: 'name', header: 'Name' },
{ id: 'location', header: 'Location', groupable: true },
{
id: 'load',
header: 'Load',
aggregate: 'sum',
exportColumns: [
{ header: 'Load %', value: (row: { load: number }) => row.load },
{ header: 'Busy', value: (row: { load: number }) => (row.load > 50 ? 'yes' : 'no') },
],
},
],
groupBy: 'location',
})
);
const sheet = sheetXml(handle!.generateXlsx());
const cells = (row: number) => [...sheet.querySelectorAll(`row[r="${row}"] c`)].map((cell) => cell.textContent);
expect(cells(1)).toEqual(['Name', 'Location', 'Load %', 'Busy']);
// Group row: the label in the first column, the sum in the first part, the second part empty
expect(cells(2)).toEqual(['Location: Frankfurt (2)', '', '113', '']);
expect(cells(3)).toEqual(['web-01', 'Frankfurt', '42', 'no']);
expect(sheet.querySelector('c[r="C3"]')!.getAttribute('t')).toBeNull();
expect(cells(4)).toEqual(['db-primary', 'Frankfurt', '71', 'yes']);
// Total row: the sum in the first part
expect(cells(7)).toEqual(['Total', '', '131', '']);
});

it('cell range: dragging and Shift+arrow keys select cells, Ctrl+C copies them as tab-separated text', async () => {
const onRange = vi.fn();
await render(framework, table({ navigation: 'grid', cellSelection: true, onCellSelectionChange: onRange }));
Expand Down
37 changes: 37 additions & 0 deletions packages/parity/src/native-data.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,43 @@ describe('export', () => {
);
});

it('exportColumns: a column becomes several columns at its position, also in the Excel sheet', () => {
const split: TableViewColumn<Server>[] = [
{
id: 'name',
header: 'Name',
exportHeader: 'unused',
exportColumns: [
{ header: 'Prefix', value: (row) => row.name.split('-')[0] },
{ header: 'Number', value: (row) => Number(row.name.split('-')[1]) },
],
},
{ id: 'city', header: 'City' },
{
id: 'load',
header: 'Load',
aggregate: 'sum',
exportColumns: [
{ header: 'Load', value: (row) => row.load },
{ header: 'Note', value: () => '' },
],
},
{ id: 'id', header: 'No.', exportable: false, exportColumns: [{ header: 'Never', value: () => 1 }] },
];
expect(tableCsv(rows.slice(0, 1), split, { bom: false })).toBe(
'Prefix;Number;City;Load;Note\r\nsrv;10;Cologne;40;'
);
const sheet = tableXlsxSheet(rows.slice(0, 2), split, { groupBy: column('city'), totalLabel: 'Total' });
expect(sheet.columns.map((part) => part.header)).toEqual(['Prefix', 'Number', 'City', 'Load', 'Note']);
expect(sheet.rows.map((row) => [row.kind ?? 'data', ...row.cells])).toEqual([
['group', 'City: Cologne (1)', null, null, 40, null],
['data', 'srv', 10, 'Cologne', 40, ''],
['group', 'City: Berlin (1)', null, null, 85, null],
['data', 'srv', 2, 'Berlin', 85, ''],
['total', 'Total', null, null, 125, null],
]);
});

it('Excel cells: numbers stay numbers, date columns become dates, yes/no stays', () => {
expect(xlsxCellValue(columns[2]!, rows[0]!)).toBe(40);
expect(xlsxCellValue(columns[3]!, rows[0]!)).toEqual({ date: '2024-03-01' });
Expand Down
49 changes: 49 additions & 0 deletions packages/react/src/data-table/DataTable.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1852,3 +1852,52 @@ export const ColumnSettings: Story = {
/>
),
};

const people = [
{ id: 'p1', firstName: 'Anna', lastName: 'Muster', club: 'TSV Nord', born: 2009 },
{ id: 'p2', firstName: 'Jonas', lastName: 'Becker', club: 'SC Süd', born: 2011 },
{ id: 'p3', firstName: 'Lea', lastName: 'Albrecht', club: 'TSV Nord', born: 2010 },
];
type Person = (typeof people)[number];
const personColumns: DataTableColumn<Person>[] = [
{
id: 'name',
header: 'Name',
accessor: (row) => `${row.lastName}, ${row.firstName}`,
exportColumns: [
{ header: 'First name', value: (row) => row.firstName },
{ header: 'Last name', value: (row) => row.lastName },
],
},
{ id: 'club', header: 'Club' },
{ id: 'born', header: 'Born', align: 'end' },
];

function ExportColumnsDemo() {
const [csv, setCsv] = useState('');
return (
<div className="flex max-w-[560px] flex-col gap-3">
<DataTable<Person>
ref={(handle: DataTableHandle | null) => {
if (handle && !csv) setCsv(handle.generateCsv({ bom: false, separator: ';' }));
}}
features={features}
data={people}
columns={personColumns}
caption="Participants"
getRowId={(row) => row.id}
exportFilename="participants"
exportFormats={['csv', 'xlsx']}
className={card}
/>
<p className="text-xs text-muted">CSV export</p>
<pre className="rounded-lg bg-bg-2 p-3 font-mono text-xs">{csv}</pre>
</div>
);
}

/**
* `exportColumns`: the table shows "Last name, first name" in one column, the CSV and Excel export split it into
* "First name" and "Last name" (printing keeps the shown column)
*/
export const ExportColumns: Story = { name: 'Export columns', render: () => <ExportColumnsDemo /> };
Loading
Loading