Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

docs(useTableColumnSettingsState): add hook docs and a column visibility picker example block (#10652)

Utkarsh patwadf5f6926ec5c
diff --git a/.changeset/hook-doc-use-table-column-settings-state.md b/.changeset/hook-doc-use-table-column-settings-state.md
new file mode 100644
index 0000000000..c9f30a91bf
--- /dev/null
+++ b/.changeset/hook-doc-use-table-column-settings-state.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[docs] Add useTableColumnSettingsState hook docs and a column visibility picker example block
+
+@utkarshpatwa393-sys
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index e1dca383db..746ebe3d4e 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -825,6 +825,7 @@
"/templates/useScrollOverflowHookUsage/",
"/templates/useScrollableAreaHookUsage/",
"/templates/useStreamingTextHookUsage/",
+ "/templates/useTableColumnSettingsStateHookUsage/",
"/templates/useTableSortableStateHookUsage/",
"/templates/useThemeHookUsage/",
"/templates/useToastHookUsage/",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 8dfbfac7f7..cc55591b68 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3916,6 +3916,11 @@
"path": "examples/use-table-column-resize/draggable-columns",
"aliases": []
},
+ {
+ "name": "example-use-table-column-settings-state-column-visibility-picker",
+ "path": "examples/use-table-column-settings-state/column-visibility-picker",
+ "aliases": []
+ },
{
"name": "example-use-table-grouped-rows-collapsible-groups",
"path": "examples/use-table-grouped-rows/collapsible-groups",
@@ -4291,6 +4296,11 @@
"path": "hooks/use-table-column-settings",
"aliases": []
},
+ {
+ "name": "hook-use-table-column-settings-state",
+ "path": "hooks/use-table-column-settings-state",
+ "aliases": []
+ },
{
"name": "hook-use-table-filter-state",
"path": "hooks/use-table-filter-state",
diff --git a/packages/cli/api/component/__fixtures__/resolutions/modules.txt b/packages/cli/api/component/__fixtures__/resolutions/modules.txt
index 7c4098115a..79773ba1be 100644
--- a/packages/cli/api/component/__fixtures__/resolutions/modules.txt
+++ b/packages/cli/api/component/__fixtures__/resolutions/modules.txt
@@ -298,7 +298,7 @@ useSpeechRecognition useSpeechRecognition Chat/Chat.doc.mjs Chat/useSpeechRecogn
useSwipeAction useSwipeAction Item/Item.doc.mjs Item/useSwipeAction.ts
useSwitchTouch useSwitchTouch Switch/Switch.doc.mjs Switch/useSwitchTouch.ts
useTableCellStyles useTableCellStyles Table/Table.doc.mjs Table/useTableCellStyles.ts
-useTableColumnSettingsState useTableColumnSettingsState Table/Table.doc.mjs Table/plugins/columnSettings/useTableColumnSettingsState.tsx
+useTableColumnSettingsState useTableColumnSettingsState Table/plugins/columnSettings/useTableColumnSettingsState.doc.mjs Table/plugins/columnSettings/useTableColumnSettingsState.tsx
useTableSortableState useTableSortableState Table/plugins/sortable/useTableSortableState.doc.mjs Table/plugins/sortable/useTableSortableState.tsx
useToastGesture useToastGesture Toast/Toast.doc.mjs Toast/useToastGesture.ts
useTouchTrigger useTouchTrigger Layer/Layer.doc.mjs Layer/useTouchTrigger.ts
diff --git a/packages/cli/api/template/use-table-column-settings-state-hook-usage.test.tsx b/packages/cli/api/template/use-table-column-settings-state-hook-usage.test.tsx
new file mode 100644
index 0000000000..ab7afbb3c4
--- /dev/null
+++ b/packages/cli/api/template/use-table-column-settings-state-hook-usage.test.tsx
@@ -0,0 +1,98 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useTableColumnSettingsState example is a members Table with a
+ * column visibility picker. Toggling Email hides the column, and
+ * clicking Reset restores the defaults.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import UseTableColumnSettingsStateHookUsage from '../../assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage';
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let root: Root | null = null;
+let container: HTMLElement;
+
+function columnHeaders(): string[] {
+ return Array.from(container.querySelectorAll('th')).map(
+ th => th.textContent?.trim() ?? '',
+ );
+}
+
+function clickButton(label: string): void {
+ const button = Array.from(document.body.querySelectorAll('button')).find(
+ b => b.textContent?.trim() === label,
+ );
+ if (button == null) {
+ throw new Error(`no button with label "${label}"`);
+ }
+ act(() => {
+ button.dispatchEvent(
+ new MouseEvent('click', {bubbles: true, cancelable: true}),
+ );
+ });
+}
+
+function clickCheckbox(label: string): void {
+ const labelElement = Array.from(document.body.querySelectorAll('label')).find(
+ l => l.textContent?.trim() === label,
+ );
+ if (labelElement == null) {
+ throw new Error(`no label with text "${label}"`);
+ }
+ const checkbox = labelElement.htmlFor
+ ? document.getElementById(labelElement.htmlFor)
+ : labelElement.querySelector('input[type="checkbox"]');
+ if (checkbox == null) {
+ throw new Error(`no checkbox for label "${label}"`);
+ }
+ act(() => {
+ checkbox.dispatchEvent(
+ new MouseEvent('click', {bubbles: true, cancelable: true}),
+ );
+ });
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UseTableColumnSettingsStateHookUsage />);
+ });
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+});
+
+describe('useTableColumnSettingsState example', () => {
+ it('renders all default columns', () => {
+ expect(columnHeaders()).toEqual(['Name', 'Email', 'Role']);
+ });
+
+ it('toggles a column off and on using the picker', () => {
+ clickButton('Columns');
+ clickCheckbox('Email');
+ expect(columnHeaders()).toEqual(['Name', 'Role']);
+
+ clickCheckbox('Email');
+ expect(columnHeaders()).toEqual(['Name', 'Role', 'Email']);
+ });
+
+ it('restores default columns on reset', () => {
+ clickButton('Columns');
+ clickCheckbox('Email');
+ expect(columnHeaders()).toEqual(['Name', 'Role']);
+
+ clickButton('Reset');
+ expect(columnHeaders()).toEqual(['Name', 'Email', 'Role']);
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage.doc.mjs
new file mode 100644
index 0000000000..b552b27b22
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'useTableColumnSettingsState',
+ name: 'useTableColumnSettingsState — Column Visibility Picker',
+ displayName: 'useTableColumnSettingsState — Column Visibility Picker',
+ description:
+ 'A Table toolbar with a Columns menu of checkboxes: toggling Email updates active columns, Reset restores defaults, and the config is passed directly to useTableColumnSettings.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Button', 'CheckboxInput', 'Popover', 'Table', 'Layout'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage.tsx
new file mode 100644
index 0000000000..ed417d9b16
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage.tsx
@@ -0,0 +1,97 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {Button} from '@astryxdesign/core/Button';
+import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';
+import {HStack, VStack} from '@astryxdesign/core/Layout';
+import {Popover} from '@astryxdesign/core/Popover';
+import {
+ Table,
+ useTableColumnSettings,
+ useTableColumnSettingsState,
+} from '@astryxdesign/core/Table';
+import type {TableColumn} from '@astryxdesign/core/Table';
+
+interface Member extends Record<string, unknown> {
+ id: string;
+ name: string;
+ email: string;
+ role: string;
+}
+
+const members: Member[] = [
+ {id: '1', name: 'Alice', email: '[email protected]', role: 'Engineer'},
+ {id: '2', name: 'Bob', email: '[email protected]', role: 'Designer'},
+ {id: '3', name: 'Charlie', email: '[email protected]', role: 'Manager'},
+];
+
+const allColumns: TableColumn<Member>[] = [
+ {key: 'name', header: 'Name'},
+ {key: 'email', header: 'Email'},
+ {key: 'role', header: 'Role'},
+];
+
+const columnOptions = [
+ {key: 'name' as const, label: 'Name', isAlwaysVisible: true},
+ {key: 'email' as const, label: 'Email'},
+ {key: 'role' as const, label: 'Role'},
+];
+
+const defaultKeys = ['name', 'email', 'role'];
+
+export default function UseTableColumnSettingsStateHookUsage() {
+ const [activeKeys, setActiveKeys] =
+ useState<ReadonlyArray<string>>(defaultKeys);
+
+ const state = useTableColumnSettingsState({
+ columns: columnOptions,
+ activeColumnKeys: activeKeys,
+ onChangeActiveColumnKeys: setActiveKeys,
+ defaultColumnKeys: defaultKeys,
+ });
+
+ const plugin = useTableColumnSettings<Member>(state.columnSettingsConfig);
+
+ return (
+ <VStack gap={3}>
+ <HStack hAlign="start">
+ <Popover
+ placement="below"
+ label="Column settings"
+ width={200}
+ content={
+ <VStack gap={2}>
+ {columnOptions.map(col => (
+ <CheckboxInput
+ key={col.key}
+ label={col.label}
+ value={state.isColumnActive(col.key)}
+ isDisabled={!state.isColumnToggleable(col.key)}
+ onChange={() => state.toggleColumn(col.key)}
+ />
+ ))}
+ <Button
+ label="Reset"
+ size="sm"
+ variant="secondary"
+ onClick={state.resetToDefault}>
+ Reset
+ </Button>
+ </VStack>
+ }>
+ <Button label="Columns" size="sm">
+ Columns
+ </Button>
+ </Popover>
+ </HStack>
+ <Table
+ data={members}
+ columns={allColumns}
+ idKey="id"
+ plugins={{columnSettings: plugin}}
+ />
+ </VStack>
+ );
+}
diff --git a/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.doc.mjs b/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.doc.mjs
new file mode 100644
index 0000000000..9055c1104e
--- /dev/null
+++ b/packages/core/src/Table/plugins/columnSettings/useTableColumnSettingsState.doc.mjs
@@ -0,0 +1,175 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useTableColumnSettingsState',
+ displayName: 'useTableColumnSettingsState',
+ group: 'Table',
+ keywords: [
+ 'table',
+ 'column',
+ 'columns',
+ 'column settings',
+ 'column visibility',
+ 'table settings',
+ 'useTableColumnSettingsState',
+ 'useTableColumnSettings',
+ ],
+ params: [
+ {
+ name: 'config',
+ type: 'UseTableColumnSettingsStateConfig<TColumnKey>',
+ description: 'The columns to configure and active keys state management.',
+ required: true,
+ },
+ {
+ name: 'config.columns',
+ type: 'ReadonlyArray<ColumnSettingsOption<TColumnKey>>',
+ description:
+ 'All available columns with metadata (key, label, isAlwaysVisible, group) for the settings UI.',
+ required: true,
+ },
+ {
+ name: 'config.activeColumnKeys',
+ type: 'ReadonlyArray<TColumnKey>',
+ description:
+ 'Currently active column keys, in display order. Only columns in this list render in the table.',
+ required: true,
+ },
+ {
+ name: 'config.onChangeActiveColumnKeys',
+ type: '(keys: ReadonlyArray<TColumnKey>) => void',
+ description:
+ 'Called when active columns change (via toggle, show all, or reset) to update consumer state.',
+ required: true,
+ },
+ {
+ name: 'config.defaultColumnKeys',
+ type: 'ReadonlyArray<TColumnKey>',
+ description:
+ 'Default column set restored by resetToDefault. When omitted, resetToDefault activates all columns.',
+ required: false,
+ },
+ ],
+ returns: [
+ {
+ name: 'columnSettingsConfig',
+ type: 'UseTableColumnSettingsStateConfig<TColumnKey>',
+ description:
+ 'Ready-to-use config to pass directly to useTableColumnSettings(columnSettingsConfig).',
+ },
+ {
+ name: 'activeColumnKeys',
+ type: 'ReadonlyArray<TColumnKey>',
+ description:
+ 'Pass-through of currently active column keys in display order.',
+ },
+ {
+ name: 'toggleColumn',
+ type: '(key: TColumnKey) => void',
+ description:
+ 'Toggles column visibility: removes an active column or appends an inactive column. No-op for isAlwaysVisible columns.',
+ },
+ {
+ name: 'isColumnActive',
+ type: '(key: TColumnKey) => boolean',
+ description:
+ 'Whether a specific column is currently in the active column keys list.',
+ },
+ {
+ name: 'isColumnToggleable',
+ type: '(key: TColumnKey) => boolean',
+ description:
+ 'Whether a specific column can be toggled (returns false if isAlwaysVisible is true).',
+ },
+ {
+ name: 'showAllColumns',
+ type: '() => void',
+ description: 'Activates all configured columns in the table.',
+ },
+ {
+ name: 'resetToDefault',
+ type: '() => void',
+ description:
+ 'Resets active column keys to defaultColumnKeys (or all columns if defaultColumnKeys is omitted).',
+ },
+ {
+ name: 'setActiveColumnKeys',
+ type: '(keys: string[]) => void',
+ description:
+ 'Sets active column keys from a list of key strings, enforcing that isAlwaysVisible columns remain active.',
+ },
+ ],
+ usage: {
+ description:
+ 'Headless column visibility and ordering state management for Table. Manages which columns are active, provides toggle and reset operations, and produces a config object that feeds directly into useTableColumnSettings. Renderer-agnostic and pairs with any column picker UI.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Pass columnSettingsConfig directly to useTableColumnSettings and give the resulting plugin to Table.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Mark essential identifier columns (like name or ID) with isAlwaysVisible: true so users cannot accidentally hide them.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Mutate activeColumnKeys array directly; use toggleColumn, showAllColumns, or resetToDefault.',
+ },
+ ],
+ },
+ relatedComponents: ['Table'],
+ relatedHooks: ['useTableColumnSettings', 'useTableSelectionState'],
+ importPath: '@astryxdesign/core/Table',
+ category: 'utilities',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Headless column visibility + ordering state for Table. Manages active columns, toggle/reset operations, produces config for useTableColumnSettings. Renderer-agnostic; pairs with any picker UI.',
+ paramDescriptions: {
+ config: 'Columns + active keys state management.',
+ 'config.columns':
+ 'All available columns with metadata (key, label, isAlwaysVisible, group).',
+ 'config.activeColumnKeys': 'Active column keys in display order.',
+ 'config.onChangeActiveColumnKeys':
+ 'Called on column toggle, show all, or reset.',
+ 'config.defaultColumnKeys':
+ 'Default column set for resetToDefault; omit to show all.',
+ },
+ returnDescriptions: {
+ columnSettingsConfig: 'Pass directly to useTableColumnSettings.',
+ activeColumnKeys: 'Active column keys in display order.',
+ toggleColumn: 'Toggles column visibility (no-op if isAlwaysVisible).',
+ isColumnActive: 'Whether column is currently active.',
+ isColumnToggleable: 'Whether column can be toggled.',
+ showAllColumns: 'Activates all columns.',
+ resetToDefault: 'Resets to defaultColumnKeys (or all columns).',
+ setActiveColumnKeys: 'Sets active keys, keeping isAlwaysVisible columns.',
+ },
+ usage: {
+ description:
+ 'Headless column visibility and ordering state for Table: provides toggle and reset operations and produces config for useTableColumnSettings.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Pass columnSettingsConfig directly to useTableColumnSettings.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Mark essential identifier columns with isAlwaysVisible: true.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Mutate activeColumnKeys directly; use provided toggle and reset operations.',
+ },
+ ],
+ },
+};