Skip to content

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

TypeScript

docs(useTableSortableState): add hook docs and a multi-sort orders example block (#9911)

Parman Mohammadalizadeh5f8a80903cbd
diff --git a/.changeset/hook-doc-use-table-sortable-state.md b/.changeset/hook-doc-use-table-sortable-state.md
new file mode 100644
index 0000000000..43413aeba6
--- /dev/null
+++ b/.changeset/hook-doc-use-table-sortable-state.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[docs] Hook docs for `useTableSortableState`, so `astryx hook useTableSortableState` and `astryx search` return it, and a `useTableSortableState — Multi-Sort Orders` example block: an orders Table with no sort code of its own, where clicking Customer and then Shift-clicking Total sorts by customer and then by total. Copy it with `astryx template useTableSortableStateHookUsage <path>`.
+
+@MannXo
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index be2d3f03f7..07f3870fd9 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -814,6 +814,7 @@
"/templates/useScrollOverflowHookUsage/",
"/templates/useScrollableAreaHookUsage/",
"/templates/useStreamingTextHookUsage/",
+ "/templates/useTableSortableStateHookUsage/",
"/templates/useThemeHookUsage/",
"/templates/useToastHookUsage/",
"/templates/useTranslatorHookUsage/",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 11ec452452..726c8ecf6a 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3861,6 +3861,11 @@
"path": "examples/use-table-selection/table-floating-bulk-actions",
"aliases": []
},
+ {
+ "name": "example-use-table-sortable-state-multi-sort-orders",
+ "path": "examples/use-table-sortable-state/multi-sort-orders",
+ "aliases": []
+ },
{
"name": "example-use-table-sticky-columns-pinned-columns",
"path": "examples/use-table-sticky-columns/pinned-columns",
@@ -4221,6 +4226,11 @@
"path": "hooks/use-table-sortable",
"aliases": []
},
+ {
+ "name": "hook-use-table-sortable-state",
+ "path": "hooks/use-table-sortable-state",
+ "aliases": []
+ },
{
"name": "hook-use-table-sticky-columns",
"path": "hooks/use-table-sticky-columns",
diff --git a/packages/cli/api/component/__fixtures__/resolutions/modules.txt b/packages/cli/api/component/__fixtures__/resolutions/modules.txt
index e3130e7a53..f13fef799e 100644
--- a/packages/cli/api/component/__fixtures__/resolutions/modules.txt
+++ b/packages/cli/api/component/__fixtures__/resolutions/modules.txt
@@ -300,7 +300,7 @@ 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
-useTableSortableState useTableSortableState Table/Table.doc.mjs Table/plugins/sortable/useTableSortableState.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
useTriggerMenu useTriggerMenu Chat/Chat.doc.mjs Chat/useTriggerMenu.tsx
diff --git a/packages/cli/api/template/use-table-sortable-state-hook-usage.test.tsx b/packages/cli/api/template/use-table-sortable-state-hook-usage.test.tsx
new file mode 100644
index 0000000000..2c835e94ee
--- /dev/null
+++ b/packages/cli/api/template/use-table-sortable-state-hook-usage.test.tsx
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useTableSortableState example is an orders Table with no sort code of
+ * its own. Clicking Customer and then Shift-clicking Total sorts by customer,
+ * then by total within each customer.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import UseTableSortableStateHookUsage from '../../assets/templates/blocks/components/Table/useTableSortableStateHookUsage';
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let root: Root | null = null;
+let container: HTMLElement;
+
+function orderIds(): string[] {
+ return Array.from(container.querySelectorAll('tbody tr')).map(
+ row => row.querySelector('td')?.textContent ?? '',
+ );
+}
+
+function sortedBy(): string {
+ return (
+ Array.from(container.querySelectorAll('span'))
+ .find(span => span.textContent?.startsWith('Sorted by:'))
+ ?.textContent?.replace('Sorted by: ', '') ?? ''
+ );
+}
+
+function clickHeader(label: string, shiftKey = false): void {
+ const button = Array.from(container.querySelectorAll('th button')).find(
+ candidate => candidate.textContent?.startsWith(label),
+ );
+ if (button == null) {
+ throw new Error(`no sortable header "${label}"`);
+ }
+ act(() => {
+ button.dispatchEvent(
+ new MouseEvent('click', {bubbles: true, cancelable: true, shiftKey}),
+ );
+ });
+}
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UseTableSortableStateHookUsage />);
+ });
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+});
+
+describe('useTableSortableState example', () => {
+ it('starts unsorted, in data order', () => {
+ expect(sortedBy()).toBe('none');
+ expect(orderIds()).toEqual([
+ '1042',
+ '1043',
+ '1044',
+ '1045',
+ '1046',
+ '1047',
+ '1048',
+ ]);
+ });
+
+ it('sorts by customer on a click, keeping data order within a customer', () => {
+ clickHeader('Customer');
+ expect(sortedBy()).toBe('customer ascending');
+ expect(orderIds()).toEqual([
+ '1043',
+ '1045',
+ '1048',
+ '1044',
+ '1047',
+ '1042',
+ '1046',
+ ]);
+ });
+
+ it('adds total as the tiebreaker on a Shift-click', () => {
+ clickHeader('Customer');
+ clickHeader('Total', true);
+ expect(sortedBy()).toBe('customer ascending, then total ascending');
+ expect(orderIds()).toEqual([
+ '1045',
+ '1048',
+ '1043',
+ '1044',
+ '1047',
+ '1046',
+ '1042',
+ ]);
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Table/useTableSortableStateHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Table/useTableSortableStateHookUsage.doc.mjs
new file mode 100644
index 0000000000..c76bc82a12
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Table/useTableSortableStateHookUsage.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: 'useTableSortableState',
+ name: 'useTableSortableState — Multi-Sort Orders',
+ displayName: 'useTableSortableState — Multi-Sort Orders',
+ description:
+ 'Orders with no sort code of their own: useTableSortableState owns the sort state, returns the sorted orders, and hands useTableSortable a ready config. Click Customer, then Shift-click Total, to sort by customer and then by total within each customer. A line above the orders reads the current sort state from the hook.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Table', 'Layout', 'Text'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Table/useTableSortableStateHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Table/useTableSortableStateHookUsage.tsx
new file mode 100644
index 0000000000..0f43c2b5eb
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Table/useTableSortableStateHookUsage.tsx
@@ -0,0 +1,61 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {VStack} from '@astryxdesign/core/Layout';
+import {
+ Table,
+ useTableSortable,
+ useTableSortableState,
+} from '@astryxdesign/core/Table';
+import type {TableColumn} from '@astryxdesign/core/Table';
+import {Text} from '@astryxdesign/core/Text';
+
+interface Order extends Record<string, unknown> {
+ id: string;
+ customer: string;
+ total: number;
+}
+
+const orders: Order[] = [
+ {id: '1042', customer: 'Chen', total: 85},
+ {id: '1043', customer: 'Ana', total: 120},
+ {id: '1044', customer: 'Ben', total: 40},
+ {id: '1045', customer: 'Ana', total: 35},
+ {id: '1046', customer: 'Chen', total: 15},
+ {id: '1047', customer: 'Ben', total: 210},
+ {id: '1048', customer: 'Ana', total: 60},
+];
+
+const columns: TableColumn<Order>[] = [
+ {key: 'id', header: 'Order'},
+ {key: 'customer', header: 'Customer', sortable: true},
+ {key: 'total', header: 'Total ($)', sortable: true, align: 'end'},
+];
+
+export default function UseTableSortableStateHookUsage() {
+ const {sortedData, sort, sortConfig} = useTableSortableState<Order>({
+ data: orders,
+ isMultiSortEnabled: true,
+ });
+ const sortablePlugin = useTableSortable<Order>(sortConfig);
+
+ return (
+ <VStack gap={3}>
+ <Text type="supporting" color="secondary">
+ Sorted by:{' '}
+ {sort.length === 0
+ ? 'none'
+ : sort
+ .map(({sortKey, direction}) => `${sortKey} ${direction}`)
+ .join(', then ')}
+ </Text>
+ <Table
+ data={sortedData}
+ columns={columns}
+ idKey="id"
+ plugins={{sortable: sortablePlugin}}
+ />
+ </VStack>
+ );
+}
diff --git a/packages/core/src/Table/plugins/sortable/useTableSortableState.doc.mjs b/packages/core/src/Table/plugins/sortable/useTableSortableState.doc.mjs
new file mode 100644
index 0000000000..f7f8b39ae9
--- /dev/null
+++ b/packages/core/src/Table/plugins/sortable/useTableSortableState.doc.mjs
@@ -0,0 +1,173 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useTableSortableState',
+ displayName: 'useTableSortableState',
+ group: 'Table',
+ keywords: [
+ 'table',
+ 'sort',
+ 'sorting',
+ 'multi-sort',
+ 'sort state',
+ 'comparator',
+ 'useTableSortable',
+ 'local sort',
+ ],
+ params: [
+ {
+ name: 'config',
+ type: 'UseTableSortableStateConfig<T, TSortKey>',
+ description: 'The rows to sort and how the sort state is owned.',
+ required: true,
+ },
+ {
+ name: 'config.data',
+ type: 'T[]',
+ description:
+ 'Rows to sort. The hook returns a sorted copy and never mutates the array.',
+ required: true,
+ },
+ {
+ name: 'config.defaultSort',
+ type: "Array<{sortKey: TSortKey, direction: 'ascending' | 'descending'}>",
+ description:
+ 'Initial sort state when the hook owns it. Ignored when sort is passed.',
+ default: '[]',
+ required: false,
+ },
+ {
+ name: 'config.sort',
+ type: "Array<{sortKey: TSortKey, direction: 'ascending' | 'descending'}>",
+ description:
+ 'Controlled sort state. Pass it with onSortChange to own the state yourself.',
+ required: false,
+ },
+ {
+ name: 'config.onSortChange',
+ type: "(sort: Array<{sortKey: TSortKey, direction: 'ascending' | 'descending'}>) => void",
+ description:
+ 'Called with the next sort state. Required when sort is passed.',
+ required: false,
+ },
+ {
+ name: 'config.comparators',
+ type: 'Partial<Record<TSortKey, (a: T, b: T) => number>>',
+ description:
+ 'Ascending comparators per sort key; the hook flips the result for descending. Keys without one compare numbers numerically, compare other values as strings with a numeric collator in the active InternationalizationProvider locale, and put null, undefined and NaN last in ascending order and first in descending.',
+ required: false,
+ },
+ {
+ name: 'config.allowUnsortedState',
+ type: 'boolean',
+ description:
+ "Passed to useTableSortable: a third click on a header returns the column to unsorted instead of 'ascending'.",
+ default: 'true',
+ required: false,
+ },
+ {
+ name: 'config.isMultiSortEnabled',
+ type: 'boolean',
+ description:
+ 'Passed to useTableSortable: Shift+click on a header adds that column as the next sort key, or steps its direction if it is already sorted, instead of replacing the sort.',
+ default: 'false',
+ required: false,
+ },
+ ],
+ returns: [
+ {
+ name: 'sortedData',
+ type: 'T[]',
+ description:
+ 'A sorted copy of data, memoized on data and the sort state. Ties keep their order in data.',
+ },
+ {
+ name: 'sort',
+ type: "Array<{sortKey: TSortKey, direction: 'ascending' | 'descending'}>",
+ description: 'The current sort state, first entry first.',
+ },
+ {
+ name: 'sortConfig',
+ type: 'UseTableSortableConfig<TSortKey>',
+ description:
+ 'Pass to useTableSortable(sortConfig) and give the resulting plugin to Table.',
+ },
+ {
+ name: 'applySort',
+ type: '(data: T[]) => T[]',
+ description:
+ 'Sorts another array with the current sort state and comparators, for a second data source or a subset.',
+ },
+ ],
+ usage: {
+ description:
+ "Owns a Table's sort state and sorts the rows locally, as a convenience layer over useTableSortable. Pass the rows in, render sortedData, and hand sortConfig to useTableSortable. The hook keeps the state (or reads it from sort and onSortChange when controlled), so header clicks re-sort the rows with no sort code in the component. With isMultiSortEnabled, Shift+click adds tiebreaker columns. For data sorted on a server, use useTableSortable directly and sort where the data lives.",
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Use it when the full data set is in memory, and pass sortedData to Table.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Add a comparator for values whose order is not their string or number value, such as a status rank.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use it for server-side or paginated-on-server data; the hook only sorts the rows it is given.',
+ },
+ ],
+ },
+ relatedComponents: ['Table'],
+ relatedHooks: ['useTableSortable', 'useCollator'],
+ importPath: '@astryxdesign/core/Table',
+ category: 'utilities',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ "Owns a Table's sort state + sorts rows locally; convenience layer over useTableSortable. Render sortedData, pass sortConfig to useTableSortable. Uncontrolled or controlled (sort + onSortChange). isMultiSortEnabled: Shift+click adds tiebreakers. Server-sorted data: use useTableSortable directly.",
+ paramDescriptions: {
+ config: 'rows + how sort state is owned.',
+ 'config.data': 'rows; returns a sorted copy, never mutates.',
+ 'config.defaultSort':
+ 'initial uncontrolled sort state; ignored when sort passed.',
+ 'config.sort': 'controlled sort state; pair with onSortChange.',
+ 'config.onSortChange': 'called with next sort state; required with sort.',
+ 'config.comparators':
+ 'ascending comparators per key (flipped for descending). Else numbers numeric, others numeric-collator strings in provider locale; null/undefined/NaN last ascending, first descending.',
+ 'config.allowUnsortedState':
+ 'to useTableSortable: third click returns to unsorted.',
+ 'config.isMultiSortEnabled':
+ 'to useTableSortable: Shift+click appends a sort key or steps its direction.',
+ },
+ returnDescriptions: {
+ sortedData: 'sorted copy, memoized on data + sort; ties keep data order.',
+ sort: 'current sort state.',
+ sortConfig: 'pass to useTableSortable; plugin goes to Table.',
+ applySort: 'sort another array with current state + comparators.',
+ },
+ usage: {
+ description:
+ 'Local sort state + sorted rows for Table over useTableSortable: render sortedData, pass sortConfig to useTableSortable. Shift+click adds tiebreakers with isMultiSortEnabled. Server-sorted data: use useTableSortable.',
+ bestPractices: [
+ {
+ guidance: true,
+ description: 'Use with in-memory data; pass sortedData to Table.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Add comparators for non-natural orders (e.g. status rank).',
+ },
+ {
+ guidance: false,
+ description: 'Use for server-side sorted/paginated data.',
+ },
+ ],
+ },
+};