diff --git a/.changeset/data-table-hidden-columns.md b/.changeset/data-table-hidden-columns.md new file mode 100644 index 0000000..6fca6d6 --- /dev/null +++ b/.changeset/data-table-hidden-columns.md @@ -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_. diff --git a/apps/storybook/src/Introduction.mdx b/apps/storybook/src/Introduction.mdx index 8f79204..450cc7a 100644 --- a/apps/storybook/src/Introduction.mdx +++ b/apps/storybook/src/Introduction.mdx @@ -359,6 +359,28 @@ const columns: DataTableColumn[] = [ `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[] = [ + { 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: diff --git a/packages/mcp/data/components.json b/packages/mcp/data/components.json index 5054203..c0e1d3a 100644 --- a/packages/mcp/data/components.json +++ b/packages/mcp/data/components.json @@ -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[] = [\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[] = [\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)", diff --git a/packages/native/src/data-table/DataTable.tsx b/packages/native/src/data-table/DataTable.tsx index bb1c903..1065ca2 100644 --- a/packages/native/src/data-table/DataTable.tsx +++ b/packages/native/src/data-table/DataTable.tsx @@ -212,7 +212,7 @@ export function DataTable({ dataSource, cacheTime = 0, searchDebounce = 300, - columns, + columns: allColumns, caption, getRowId, rowLabel, @@ -268,6 +268,8 @@ export function DataTable({ 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); diff --git a/packages/native/src/data-table/types.ts b/packages/native/src/data-table/types.ts index d18ab13..04e1e33 100644 --- a/packages/native/src/data-table/types.ts +++ b/packages/native/src/data-table/types.ts @@ -68,6 +68,11 @@ export interface DataTableColumn { 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`) */ diff --git a/packages/parity/e2e/visual/__screenshots__/react-data-datatable--optional-columns.png b/packages/parity/e2e/visual/__screenshots__/react-data-datatable--optional-columns.png new file mode 100644 index 0000000..1aee666 Binary files /dev/null and b/packages/parity/e2e/visual/__screenshots__/react-data-datatable--optional-columns.png differ diff --git a/packages/parity/src/data-table.test.ts b/packages/parity/src/data-table.test.ts index 9472057..feb8a0c 100644 --- a/packages/parity/src/data-table.test.ts +++ b/packages/parity/src/data-table.test.ts @@ -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'; @@ -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(); diff --git a/packages/react/src/data-table/DataTable.stories.tsx b/packages/react/src/data-table/DataTable.stories.tsx index c8ba653..9aaa7c5 100644 --- a/packages/react/src/data-table/DataTable.stories.tsx +++ b/packages/react/src/data-table/DataTable.stories.tsx @@ -1901,3 +1901,28 @@ function ExportColumnsDemo() { * "First name" and "Last name" (printing keeps the shown column) */ export const ExportColumns: Story = { name: 'Export columns', render: () => }; + +/** + * `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: () => ( + + 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]`} + /> + ), +}; diff --git a/packages/react/src/data-table/DataTable.tsx b/packages/react/src/data-table/DataTable.tsx index 4aed32d..8d65734 100644 --- a/packages/react/src/data-table/DataTable.tsx +++ b/packages/react/src/data-table/DataTable.tsx @@ -56,7 +56,10 @@ import { isActiveFilter, isRangeMatchMode, listValueKey, + hiddenColumnDefaults, loadTableState, + restoreHiddenColumns, + tableColumnIds, locateTreeNode, matchesColumnFilter, matchesRowKeywords, @@ -954,7 +957,10 @@ export function DataTable({ () => (filtersValue === undefined ? internalFilters : fromFilters(filtersValue)), [filtersValue, internalFilters] ); - const [internalHidden, setInternalHidden] = useState({}); + // Without hiddenColumns the columns with `hidden: true` start hidden + const [internalHidden, setInternalHidden] = useState(() => + toIds(hiddenColumnDefaults(columnsProp), false) + ); const hiddenValue = useSameValue(hiddenColumns); const columnVisibility = useMemo( () => (hiddenValue === undefined ? internalHidden : toIds(hiddenValue, false)), @@ -2947,7 +2953,9 @@ export function DataTable({ 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)); @@ -2967,6 +2975,7 @@ export function DataTable({ 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]), diff --git a/packages/react/src/data-table/types.ts b/packages/react/src/data-table/types.ts index 9155368..1c4cc58 100644 --- a/packages/react/src/data-table/types.ts +++ b/packages/react/src/data-table/types.ts @@ -195,6 +195,12 @@ export interface DataTableColumn { 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 */ diff --git a/packages/recipes/src/data-table.ts b/packages/recipes/src/data-table.ts index 35fc7ac..162f153 100644 --- a/packages/recipes/src/data-table.ts +++ b/packages/recipes/src/data-table.ts @@ -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'; @@ -391,6 +392,8 @@ export interface DataTableState { columnSizing?: Record; 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[]; @@ -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' diff --git a/packages/recipes/src/index.ts b/packages/recipes/src/index.ts index 2945a06..a5704d1 100644 --- a/packages/recipes/src/index.ts +++ b/packages/recipes/src/index.ts @@ -555,6 +555,9 @@ export { nextSorting, numberSummary, omitTableState, + hiddenColumnDefaults, + restoreHiddenColumns, + tableColumnIds, printHtml, printTableHtml, saveTableState, diff --git a/packages/vue/src/data-table/DataTable.stories.ts b/packages/vue/src/data-table/DataTable.stories.ts index a129cb0..7a12421 100644 --- a/packages/vue/src/data-table/DataTable.stories.ts +++ b/packages/vue/src/data-table/DataTable.stories.ts @@ -2257,3 +2257,38 @@ export const ExportColumns: Story = { `, }), }; + +/** + * `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: () => ({ + components: { DataTable: DataTable as ConcreteComponent }, + setup: () => ({ + features, + rows: people, + card, + getRowId: (row: Person) => row.id, + columns: [ + { id: 'name', header: 'Name', accessor: (row: Person) => `${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' }, + ], + }), + template: ` + `, + }), +}; diff --git a/packages/vue/src/data-table/DataTable.vue b/packages/vue/src/data-table/DataTable.vue index 5df7065..1cfd56d 100644 --- a/packages/vue/src/data-table/DataTable.vue +++ b/packages/vue/src/data-table/DataTable.vue @@ -89,7 +89,10 @@ import { isActiveFilter, isRangeMatchMode, listValueKey, + hiddenColumnDefaults, loadTableState, + restoreHiddenColumns, + tableColumnIds, locateTreeNode, matchesColumnFilter, matchesRowKeywords, @@ -859,7 +862,10 @@ watchProp( () => props.filters, (value) => value && (columnFilters.value = fromFilters(value)) ); -const columnVisibility = ref(toIds(props.hiddenColumns ?? [], false)); +// Without hiddenColumns the columns with `hidden: true` start hidden +const columnVisibility = ref( + toIds(props.hiddenColumns ?? hiddenColumnDefaults(props.columns), false) +); watchProp( () => props.hiddenColumns, (ids) => ids && (columnVisibility.value = toIds(ids, false)) @@ -3016,6 +3022,7 @@ const tableState = computed(() => ({ columnSizing: columnSizing.value, columnOrder: columnOrder.value, hiddenColumns: Object.keys(columnVisibility.value).filter((key) => columnVisibility.value[key] === false), + knownColumns: tableColumnIds(props.columns), pinnedColumns: columnPinning.value, expanded: expanded.value === true @@ -3035,7 +3042,9 @@ onMounted(() => { if (saved.globalFilter !== undefined) table.setGlobalFilter(saved.globalFilter); if (saved.columnSizing) columnSizing.value = 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(props.columns)); + 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)); diff --git a/packages/vue/src/data-table/types.ts b/packages/vue/src/data-table/types.ts index 981c524..9c31c6b 100644 --- a/packages/vue/src/data-table/types.ts +++ b/packages/vue/src/data-table/types.ts @@ -192,6 +192,12 @@ export interface DataTableColumn { 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 */