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
13 changes: 13 additions & 0 deletions .changeset/data-table-hidden-columns.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@wirecore/wirelayer-recipes': minor
'@wirecore/wirelayer-vue': minor
'@wirecore/wirelayer-react': minor
'@wirecore/wirelayer-native': minor
---

DataTable: column option `hidden` – the column starts hidden and is shown with the column menu (`columnToggle`). A saved
state (`stateKey`) now also lists the columns it knows (`knownColumns`): it keeps the user's choice for those, and a
column added later starts with its `hidden` value instead of suddenly showing for everyone with a saved state; a state
saved before treats every column with `hidden` as new. While `hiddenColumns` is set it decides alone; `hideable: false`
wins over `hidden` (warning in development). React Native has no column menu: a column with `hidden` is not shown.
New recipe helpers `hiddenColumnDefaults`, `restoreHiddenColumns` and `tableColumnIds`. Story _Optional columns_.
22 changes: 22 additions & 0 deletions apps/storybook/src/Introduction.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,28 @@ const columns: DataTableColumn<Person>[] = [
`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.

## DataTable: hidden columns and saved state

A column with `hidden: true` starts hidden; the column menu (`columnToggle`) shows it. Hidden columns are neither
exported nor printed. `hiddenColumns` (v-model) sets the hidden columns of the whole table – while it is set, its value
decides alone and `hidden` is not used. `hideable: false` wins over `hidden` (with a warning in development).

`stateKey` saves sorting, filters, widths, order and the hidden columns in the browser (`stateStorage`: session or
local) and restores them on the next visit; `stateExclude` leaves parts out. The saved state also lists the columns it
knows (`knownColumns`): for those the user's choice stays, a column added later starts with its `hidden` value – an
optional column does not suddenly appear for users with a saved state. A state saved before (without `knownColumns`)
treats every column with `hidden` as new.

```ts
const columns: DataTableColumn<Person>[] = [
{ id: 'name', header: 'Name', accessor: (row) => `${row.lastName}, ${row.firstName}` },
{ id: 'firstName', header: 'First name', sortable: true, hidden: true, exportable: false },
{ id: 'lastName', header: 'Last name', sortable: true, hidden: true, exportable: false },
];
```

The React Native DataTable has no column menu: a column with `hidden` is not shown there.

## 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 @@ -38151,6 +38151,11 @@
"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-datatable-hidden-columns-and-saved-state",
"title": "DataTable: hidden columns and saved state",
"text": "A column with `hidden: true` starts hidden; the column menu (`columnToggle`) shows it. Hidden columns are neither\nexported nor printed. `hiddenColumns` (v-model) sets the hidden columns of the whole table – while it is set, its value\ndecides alone and `hidden` is not used. `hideable: false` wins over `hidden` (with a warning in development).\n\n`stateKey` saves sorting, filters, widths, order and the hidden columns in the browser (`stateStorage`: session or\nlocal) and restores them on the next visit; `stateExclude` leaves parts out. The saved state also lists the columns it\nknows (`knownColumns`): for those the user's choice stays, a column added later starts with its `hidden` value – an\noptional column does not suddenly appear for users with a saved state. A state saved before (without `knownColumns`)\ntreats every column with `hidden` as new.\n\n```ts\nconst columns: DataTableColumn<Person>[] = [\n { id: 'name', header: 'Name', accessor: (row) => `${row.lastName}, ${row.firstName}` },\n { id: 'firstName', header: 'First name', sortable: true, hidden: true, exportable: false },\n { id: 'lastName', header: 'Last name', sortable: true, hidden: true, exportable: false },\n];\n```\n\nThe React Native DataTable has no column menu: a column with `hidden` is not shown there."
},
{
"id": "introduction-ai-assistants-mcp-llms-txt",
"title": "AI assistants (MCP, llms.txt)",
Expand Down
4 changes: 3 additions & 1 deletion packages/native/src/data-table/DataTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ export function DataTable<TData extends object>({
dataSource,
cacheTime = 0,
searchDebounce = 300,
columns,
columns: allColumns,
caption,
getRowId,
rowLabel,
Expand Down Expand Up @@ -268,6 +268,8 @@ export function DataTable<TData extends object>({
const { translations, locale } = useLocale();
const t = translations.dataTable;
const styles = dataTable();
// `hidden`: no column menu here – such a column is neither shown nor exported
const columns = useMemo(() => allColumns.filter((column) => !column.hidden), [allColumns]);
const web = Platform.OS === 'web';
const screen = useWindowDimensions();
const [width, setWidth] = useState(0);
Expand Down
5 changes: 5 additions & 0 deletions packages/native/src/data-table/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ export interface DataTableColumn<TData> {
aggregate?: DataTableAggregate | ((values: unknown[]) => unknown);
/** Footer text of the column (instead of the aggregate) */
footer?: string;
/**
* The column is not shown and not exported – the React Native DataTable has no column menu to show it (on the web
* the column starts hidden)
*/
hidden?: boolean;
/** Part of the export, default true */
exportable?: boolean;
/** Column name in the export (default: `header`) */
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
73 changes: 72 additions & 1 deletion packages/parity/src/data-table.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import {
xlsxSheetName,
zipStore,
} from '@wirecore/wirelayer-recipes';
import { describe, expect, it, vi } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { defineComponent, h, nextTick, ref, type Component } from 'vue';
import { el, feature, frameworks, render, toReact, type El } from './harness.js';
import { de as german } from '@wirecore/wirelayer-recipes/locales/de';
Expand Down Expand Up @@ -2681,6 +2681,77 @@ describe.each(frameworks)('%s DataTable: reset, saved state, column settings', (
}
};

describe('hidden columns', () => {
// "Since" is offered in the column menu, hidden at the start
const optional = [...columns, { id: 'since', header: 'Since', hidden: true }];
const headers = () => screen.getAllByRole('columnheader').map((header) => header.textContent?.trim());
const saved = (state: object) => sessionStorage.setItem('wirecore-table:hidden-test', JSON.stringify(state));
afterEach(() => sessionStorage.clear());

it('a column with hidden starts hidden, the column menu shows it; the export follows', async () => {
let handle: { generateCsv: (options?: object) => string } | undefined;
await render(
framework,
table({
columns: optional,
columnToggle: true,
ref: (value: typeof handle | null) => (handle = value ?? handle),
})
);
expect(headers()).toEqual(['Name', 'Location', 'Load']);
expect(handle!.generateCsv({ bom: false }).split('\r\n')[0]).toBe('Name,Location,Load');
const user = userEvent.setup();
await user.click(screen.getByRole('button', { name: 'Columns' }));
const since = await screen.findByRole('menuitemcheckbox', { name: 'Since' });
expect(since).toHaveAttribute('aria-checked', 'false');
await user.click(since);
await waitFor(() => expect(headers()).toEqual(['Name', 'Location', 'Load', 'Since']));
expect(handle!.generateCsv({ bom: false }).split('\r\n')[0]).toBe('Name,Location,Load,Since');
});

it('hiddenColumns set: its value decides alone', async () => {
await render(framework, table({ columns: optional, hiddenColumns: ['location'] }));
expect(headers()).toEqual(['Name', 'Load', 'Since']);
});

it('hideable: false wins over hidden', async () => {
await render(
framework,
table({ columns: [...columns, { id: 'since', header: 'Since', hidden: true, hideable: false }] })
);
expect(headers()).toEqual(['Name', 'Location', 'Load', 'Since']);
});

it('saved state that does not know the column: it starts hidden, the rest as saved', async () => {
// Saved before "Since" existed
saved({ hiddenColumns: ['location'], knownColumns: ['name', 'location', 'load'] });
await render(framework, table({ columns: optional, stateKey: 'hidden-test' }));
await waitFor(() => expect(headers()).toEqual(['Name', 'Load']));
});

it('saved state that knows the column: the choice of the user stays', async () => {
// The user showed "Since" before
saved({ hiddenColumns: [], knownColumns: ['name', 'location', 'load', 'since'] });
await render(framework, table({ columns: optional, stateKey: 'hidden-test' }));
await waitFor(() => expect(headers()).toEqual(['Name', 'Location', 'Load', 'Since']));
});

it('saved state without knownColumns (older): hidden columns start hidden; saving adds the known columns', async () => {
saved({ hiddenColumns: ['location'] });
await render(framework, table({ columns: optional, stateKey: 'hidden-test', columnToggle: true }));
await waitFor(() => expect(headers()).toEqual(['Name', 'Load']));
const user = userEvent.setup();
await user.click(screen.getByRole('button', { name: 'Columns' }));
await user.click(await screen.findByRole('menuitemcheckbox', { name: 'Since' }));
await waitFor(() =>
expect(JSON.parse(sessionStorage.getItem('wirecore-table:hidden-test')!)).toMatchObject({
hiddenColumns: ['location'],
knownColumns: ['name', 'location', 'load', 'since'],
})
);
});
});

it('filterReset: a toolbar button clears the filters and the search; disabled while nothing is set', async () => {
const onFilters = vi.fn();
const onSearch = vi.fn();
Expand Down
25 changes: 25 additions & 0 deletions packages/react/src/data-table/DataTable.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1901,3 +1901,28 @@ function ExportColumnsDemo() {
* "First name" and "Last name" (printing keeps the shown column)
*/
export const ExportColumns: Story = { name: 'Export columns', render: () => <ExportColumnsDemo /> };

/**
* `hidden`: "First name" and "Last name" start hidden next to the combined "Name" – shown with the column menu, sortable
* on their own; a saved state (`stateKey`) keeps the choice and hides columns it does not know yet
*/
export const OptionalColumns: Story = {
name: 'Optional columns',
render: () => (
<DataTable<Person>
features={features}
data={people}
columns={[
{ id: 'name', header: 'Name', accessor: (row) => `${row.lastName}, ${row.firstName}` },
{ id: 'firstName', header: 'First name', sortable: true, hidden: true, exportable: false },
{ id: 'lastName', header: 'Last name', sortable: true, hidden: true, exportable: false },
{ id: 'club', header: 'Club' },
{ id: 'born', header: 'Born', align: 'end' },
]}
caption="Participants"
getRowId={(row) => row.id}
columnToggle
className={`${card} max-w-[640px]`}
/>
),
};
13 changes: 11 additions & 2 deletions packages/react/src/data-table/DataTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,10 @@ import {
isActiveFilter,
isRangeMatchMode,
listValueKey,
hiddenColumnDefaults,
loadTableState,
restoreHiddenColumns,
tableColumnIds,
locateTreeNode,
matchesColumnFilter,
matchesRowKeywords,
Expand Down Expand Up @@ -954,7 +957,10 @@ export function DataTable<TData extends object>({
() => (filtersValue === undefined ? internalFilters : fromFilters(filtersValue)),
[filtersValue, internalFilters]
);
const [internalHidden, setInternalHidden] = useState<ColumnVisibilityState>({});
// Without hiddenColumns the columns with `hidden: true` start hidden
const [internalHidden, setInternalHidden] = useState<ColumnVisibilityState>(() =>
toIds(hiddenColumnDefaults(columnsProp), false)
);
const hiddenValue = useSameValue(hiddenColumns);
const columnVisibility = useMemo(
() => (hiddenValue === undefined ? internalHidden : toIds(hiddenValue, false)),
Expand Down Expand Up @@ -2947,7 +2953,9 @@ export function DataTable<TData extends object>({
if (saved.globalFilter !== undefined) table.setGlobalFilter(saved.globalFilter);
if (saved.columnSizing) setColumnSizing(saved.columnSizing);
if (saved.columnOrder) table.setColumnOrder(saved.columnOrder);
if (saved.hiddenColumns) table.setColumnVisibility(toIds(saved.hiddenColumns, false));
// The user's choice for the columns the state knows, `hidden` for the new ones
const hidden = restoreHiddenColumns(saved, hiddenColumnDefaults(columnsProp));
if (hidden) table.setColumnVisibility(toIds(hidden, false));
if (saved.pinnedColumns) table.setColumnPinning(saved.pinnedColumns);
if (saved.expanded && saved.expanded.length) setExpanded(toIds(saved.expanded));
if (saved.selection) setSelection(toSelection(saved.selection));
Expand All @@ -2967,6 +2975,7 @@ export function DataTable<TData extends object>({
columnSizing,
columnOrder,
hiddenColumns: Object.keys(columnVisibility).filter((key) => columnVisibility[key] === false),
knownColumns: tableColumnIds(columnsProp),
pinnedColumns: columnPinning,
expanded: expanded === true ? [] : Object.keys(expanded).filter((key) => expanded[key]),
selection: Object.keys(rowSelection).filter((key) => rowSelection[key]),
Expand Down
6 changes: 6 additions & 0 deletions packages/react/src/data-table/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,12 @@ export interface DataTableColumn<TData> {
width?: number;
/** Stays visible at the start or end while the table scrolls sideways */
pinned?: 'start' | 'end';
/**
* The column starts hidden; it is shown with the column menu (`columnToggle`) or `hiddenColumns`. With
* `hiddenColumns` (v-model) set, that value decides alone. A saved state (`stateKey`) keeps the user's choice for the
* columns it knows; columns it does not know yet start with this value. Ignored with `hideable: false`
*/
hidden?: boolean;
/** Can be hidden in the column menu (`columnToggle`), default true */
hideable?: boolean;
/** Hidden on screens below this breakpoint */
Expand Down
43 changes: 43 additions & 0 deletions packages/recipes/src/data-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// with match modes, sorting clicks, aggregation, row ranges and the saved table state. Both packages call these,
// so Vue and React filter, sort and store alike.

import { warnInDevelopment } from './dev.js';
import { moveTreeNode } from './hierarchy.js';
import { listValueKey } from './list-items.js';

Expand Down Expand Up @@ -391,6 +392,8 @@ export interface DataTableState {
columnSizing?: Record<string, number>;
columnOrder?: string[];
hiddenColumns?: string[];
/** Ids of the columns the state knows – a column with `hidden` it does not know starts hidden */
knownColumns?: string[];
pinnedColumns?: { start: string[]; end: string[] };
expanded?: string[];
selection?: string[];
Expand All @@ -407,9 +410,49 @@ export function omitTableState(state: DataTableState, exclude: readonly DataTabl
if (!exclude.length) return state;
const kept = { ...state };
for (const key of exclude) delete kept[key];
// The known columns only matter next to the hidden ones
if (exclude.includes('hiddenColumns')) delete kept.knownColumns;
return kept;
}

/** A column (or column group) for `hiddenColumnDefaults` */
interface HideableColumn {
id: string;
hidden?: boolean;
hideable?: boolean;
columns?: readonly HideableColumn[];
}

/** Ids of the columns (of column groups too) with `hidden: true` – they start hidden; `hideable: false` wins */
export function hiddenColumnDefaults(columns: readonly HideableColumn[]): string[] {
return columns.flatMap((column) => {
if (column.columns) return hiddenColumnDefaults(column.columns);
if (!column.hidden) return [];
if (column.hideable === false) {
warnInDevelopment(
`DataTable: column "${column.id}" has hidden: true and hideable: false – it stays shown, hidden is ignored.`
);
return [];
}
return [column.id];
});
}

/** Ids of all columns (leaves of column groups) – the `knownColumns` of a saved state */
export function tableColumnIds(columns: readonly HideableColumn[]): string[] {
return columns.flatMap((column) => (column.columns ? tableColumnIds(column.columns) : [column.id]));
}

/**
* The hidden columns of a saved state: the user's choice for the columns it knows, `defaults` (`hiddenColumnDefaults`)
* for the others. A state without `knownColumns` (saved before) knows none of the `defaults`.
*/
export function restoreHiddenColumns(saved: DataTableState, defaults: readonly string[]): string[] | undefined {
if (!saved.hiddenColumns) return undefined;
const known = new Set(saved.knownColumns ?? []);
return [...new Set([...saved.hiddenColumns, ...defaults.filter((id) => !known.has(id))])];
}

const storageOf = (kind: 'local' | 'session') => {
try {
return typeof window === 'undefined'
Expand Down
3 changes: 3 additions & 0 deletions packages/recipes/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,9 @@ export {
nextSorting,
numberSummary,
omitTableState,
hiddenColumnDefaults,
restoreHiddenColumns,
tableColumnIds,
printHtml,
printTableHtml,
saveTableState,
Expand Down
Loading
Loading