Skip to content

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

TypeScript

feat(Table): the sort indicator resolves its glyph through the table-sort-indicator icon slot (#9831)

Xinzi Zhouf85b20173e3b
diff --git a/.changeset/component-icon-slot-table-sort-indicator.md b/.changeset/component-icon-slot-table-sort-indicator.md
new file mode 100644
index 0000000000..7952474d39
--- /dev/null
+++ b/.changeset/component-icon-slot-table-sort-indicator.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Table: a sortable column's sort indicator resolves its glyph through the `table-sort-indicator` component icon slot with state `{direction}` (`'ascending' | 'descending' | 'none'`). With no theme entry it draws `arrowUp`, `arrowDown`, or `arrowsUpDown`, as before. A theme maps it with `defineTheme({componentIcons: {'table-sort-indicator': …}})`; `null` hides only the glyph, and the sort control keeps its label, its sorting, and the header's `aria-sort`.
+
+@imdreamrunner
diff --git a/apps/storybook/stories/TableSortable.stories.tsx b/apps/storybook/stories/TableSortable.stories.tsx
index 0a9b28ca2f..8787749405 100644
--- a/apps/storybook/stories/TableSortable.stories.tsx
+++ b/apps/storybook/stories/TableSortable.stories.tsx
@@ -11,6 +11,7 @@ import {
} from '@astryxdesign/core/Table';
import type {TableColumn, TableSortState} from '@astryxdesign/core/Table';
import {useCollator} from '@astryxdesign/core';
+import {defineTheme, Theme} from '@astryxdesign/core/theme';
// =============================================================================
// Sample Data
@@ -319,3 +320,58 @@ export const Controlled: Story = {
);
},
};
+
+const largeIndicatorTheme = defineTheme({
+ name: 'story-large-sort-indicator',
+ componentIcons: {'table-sort-indicator': {size: 'lg'}},
+});
+
+const hiddenIndicatorTheme = defineTheme({
+ name: 'story-hidden-sort-indicator',
+ componentIcons: {'table-sort-indicator': null},
+});
+
+/**
+ * The same sorted table with the default indicator, with a theme that asks
+ * the `table-sort-indicator` slot for a large glyph, and with a theme that
+ * hides it. The large glyph grows while the Sort control and the header row
+ * keep their height; the hidden glyph leaves no gap beside the label.
+ */
+export const IndicatorSlotSize: Story = {
+ render: () => {
+ const sort: TableSortState = [{sortKey: 'name', direction: 'ascending'}];
+ const sortPlugin = useTableSortable<Employee>({
+ sort,
+ onSortChange: () => {},
+ });
+ return (
+ <div style={{display: 'grid', gap: 24}}>
+ <div data-testid="default-indicator">
+ <Table
+ data={employees}
+ columns={columns}
+ plugins={{sort: sortPlugin}}
+ />
+ </div>
+ <Theme theme={largeIndicatorTheme}>
+ <div data-testid="large-indicator">
+ <Table
+ data={employees}
+ columns={columns}
+ plugins={{sort: sortPlugin}}
+ />
+ </div>
+ </Theme>
+ <Theme theme={hiddenIndicatorTheme}>
+ <div data-testid="hidden-indicator">
+ <Table
+ data={employees}
+ columns={columns}
+ plugins={{sort: sortPlugin}}
+ />
+ </div>
+ </Theme>
+ </div>
+ );
+ },
+};
diff --git a/packages/core/src/Icon/componentIcons.test.tsx b/packages/core/src/Icon/componentIcons.test.tsx
index c4f056bc33..f5a6d1be11 100644
--- a/packages/core/src/Icon/componentIcons.test.tsx
+++ b/packages/core/src/Icon/componentIcons.test.tsx
@@ -349,6 +349,7 @@ describe('component icon slot types', () => {
expectTypeOf<ComponentIconSlotName>().toEqualTypeOf<
| 'code-block-copy'
| 'timestamp-copy'
+ | 'table-sort-indicator'
| 'example-panel-dismiss'
| 'example-nav-item-leading'
>();
diff --git a/packages/core/src/Icon/index.ts b/packages/core/src/Icon/index.ts
index 5299091f1d..520f80602a 100644
--- a/packages/core/src/Icon/index.ts
+++ b/packages/core/src/Icon/index.ts
@@ -66,6 +66,10 @@ export interface ComponentIconSlotMap {
'code-block-copy': {readonly copied: boolean};
/** A Timestamp hover card row's copy button. `copied` is true while the copied feedback shows. */
'timestamp-copy': {readonly copied: boolean};
+ /** A sortable Table column's sort indicator, by the column's sort direction. */
+ 'table-sort-indicator': {
+ readonly direction: 'ascending' | 'descending' | 'none';
+ };
}
/** A slot name from the augmentable {@link ComponentIconSlotMap}. */
diff --git a/packages/core/src/Table/Table.doc.mjs b/packages/core/src/Table/Table.doc.mjs
index 62540e0d10..df87dec2dc 100644
--- a/packages/core/src/Table/Table.doc.mjs
+++ b/packages/core/src/Table/Table.doc.mjs
@@ -143,6 +143,25 @@ export const docs = {
{className: 'astryx-table-cell', visualProps: ['density']},
{className: 'astryx-table-header-cell', visualProps: ['density']},
],
+ componentIcons: [
+ {
+ slot: 'table-sort-indicator',
+ description:
+ "The sort direction glyph beside a sortable column's label (`useTableSortable`).",
+ fallback:
+ '`arrowUp` ascending; `arrowDown` descending; `arrowsUpDown` unsorted',
+ state: [
+ {
+ name: 'direction',
+ type: "'ascending' | 'descending' | 'none'",
+ description:
+ "The column's sort direction; `none` while the column is not sorted.",
+ },
+ ],
+ whenNull:
+ 'Hides the glyph. The Sort control keeps its label and its click and keyboard sorting; the column header keeps `aria-sort`.',
+ },
+ ],
},
description:
'Styled, data-driven table with density, dividers, hover highlight, striped rows, and named plugin support. T must extend Record<string, unknown>.',
diff --git a/packages/core/src/Table/__tests__/TableSortIndicatorSlot.a11y.browser.spec.ts b/packages/core/src/Table/__tests__/TableSortIndicatorSlot.a11y.browser.spec.ts
new file mode 100644
index 0000000000..9cfcc348fe
--- /dev/null
+++ b/packages/core/src/Table/__tests__/TableSortIndicatorSlot.a11y.browser.spec.ts
@@ -0,0 +1,86 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope ^packages/core/src/Table/plugins/sortable/ ^packages/core/src/Icon/ComponentIcon ^apps/storybook/stories/TableSortable
+
+/**
+ * @file TableSortIndicatorSlot.a11y.browser.spec.ts
+ * @input The built TableSortable IndicatorSlotSize story in real Chromium and
+ * WebKit
+ * @output Browser evidence that a theme's `table-sort-indicator` size request
+ * changes only the glyph (component:Table FR5): the Sort control and the
+ * header row keep the height they have with the default glyph; a hidden
+ * glyph leaves no gap beside the label
+ * @position Regression proof for the sort indicator wrapper's fixed block size
+ */
+
+import {expect, test} from '@astryxdesign/a11y-spec/playwright';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+test('a large sort indicator glyph keeps the Sort control and header height', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tablesortable--indicator-slot-size&viewMode=story`,
+ );
+ const measure = async (testId: string) => {
+ const table = page.getByTestId(testId);
+ const header = table.getByRole('columnheader', {name: 'Name'});
+ const control = header.getByRole('button', {name: 'Name'});
+ const glyph = control.locator('.astryx-icon');
+ await expect(glyph).toBeVisible();
+ const [headerBox, controlBox, glyphBox] = await Promise.all([
+ header.boundingBox(),
+ control.boundingBox(),
+ glyph.boundingBox(),
+ ]);
+ return {
+ header: headerBox?.height,
+ control: controlBox?.height,
+ glyph: glyphBox?.height,
+ };
+ };
+
+ const normal = await measure('default-indicator');
+ const large = await measure('large-indicator');
+
+ // The slot reached the glyph.
+ expect(large.glyph).toBeGreaterThan(normal.glyph ?? Infinity);
+ // The control and the row around it did not move.
+ expect(large.control).toBeCloseTo(normal.control ?? 0, 1);
+ expect(large.header).toBeCloseTo(normal.header ?? 0, 1);
+});
+
+test('a hidden sort indicator leaves no gap beside the label', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-tablesortable--indicator-slot-size&viewMode=story`,
+ );
+ const control = page
+ .getByTestId('hidden-indicator')
+ .getByRole('columnheader', {name: 'Name'})
+ .getByRole('button', {name: 'Name'});
+ await expect(control).toBeVisible();
+ // The label is the control's only laid-out child: the empty indicator
+ // wrapper collapses, so the button's gap does not follow the label.
+ const laidOut = await control.evaluate(
+ button =>
+ [...button.children].filter(child => child.getClientRects().length > 0)
+ .length,
+ );
+ expect(laidOut).toBe(1);
+ await expect(control.locator('.astryx-icon')).toHaveCount(0);
+});
diff --git a/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx b/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx
index 1a8d3db226..d6c6b3d3bb 100644
--- a/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx
+++ b/packages/core/src/Table/plugins/sortable/useTableSortable.test.tsx
@@ -15,6 +15,9 @@ import {Table} from '../../Table';
import {InternationalizationProvider} from '../../../i18n';
import type {TableColumn} from '../../types';
import {useTableSortable, type TableSortState} from './useTableSortable';
+import type {ComponentIconMap} from '../../../Icon/index';
+import {defineTheme} from '../../../theme/defineTheme';
+import {Theme} from '../../../theme/Theme';
// =============================================================================
// Test Data
@@ -784,3 +787,105 @@ describe('useTableSortable — header alignment', () => {
expect(buttonFor(/^age$/i).className).toBe(buttonFor(/^name$/i).className);
});
});
+
+describe('sort indicator icon slot', () => {
+ // Label each shared icon's artwork, so a test reads which name rendered.
+ const icons = {
+ arrowUp: <span data-icon="arrowUp" />,
+ arrowDown: <span data-icon="arrowDown" />,
+ arrowsUpDown: <span data-icon="arrowsUpDown" />,
+ chevronDown: <span data-icon="chevronDown" />,
+ chevronRight: <span data-icon="chevronRight" />,
+ };
+ let themeCount = 0;
+
+ function renderSorted(
+ componentIcons?: ComponentIconMap<never>,
+ initialSort: TableSortState = [{sortKey: 'name', direction: 'ascending'}],
+ ) {
+ const theme = defineTheme({
+ name: `table-sort-slot-${themeCount++}`,
+ icons,
+ componentIcons,
+ });
+ render(
+ <Theme theme={theme}>
+ <SortableTable initialSort={initialSort} />
+ </Theme>,
+ );
+ }
+
+ const glyph = (name: string) =>
+ screen
+ .getByRole('button', {name})
+ .querySelector('[data-icon]')
+ ?.getAttribute('data-icon') ?? null;
+
+ it('draws arrowUp, arrowDown, or arrowsUpDown by direction when the theme maps nothing', () => {
+ renderSorted(undefined, [{sortKey: 'age', direction: 'descending'}]);
+ expect(glyph('Age')).toBe('arrowDown');
+ expect(glyph('Name')).toBe('arrowsUpDown');
+ fireEvent.click(screen.getByRole('button', {name: 'Name'}));
+ expect(glyph('Name')).toBe('arrowUp');
+ });
+
+ it('passes the direction to a slot function, with none for an unsorted column', () => {
+ const slot = vi.fn(
+ ({direction}: {direction: 'ascending' | 'descending' | 'none'}) =>
+ direction === 'none'
+ ? null
+ : {
+ icon:
+ direction === 'ascending'
+ ? ('chevronRight' as const)
+ : ('chevronDown' as const),
+ },
+ );
+ renderSorted({'table-sort-indicator': slot});
+
+ expect(glyph('Name')).toBe('chevronRight');
+ expect(glyph('Age')).toBeNull();
+ expect(slot).toHaveBeenCalledWith({direction: 'ascending'});
+ expect(slot).toHaveBeenCalledWith({direction: 'none'});
+ fireEvent.click(screen.getByRole('button', {name: 'Name'}));
+ expect(glyph('Name')).toBe('chevronDown');
+ expect(slot).toHaveBeenCalledWith({direction: 'descending'});
+ });
+
+ it('hides only the glyph for null; sorting and aria-sort still work', () => {
+ const onSortChange = vi.fn();
+ const theme = defineTheme({
+ name: `table-sort-slot-${themeCount++}`,
+ componentIcons: {'table-sort-indicator': null},
+ });
+ render(
+ <Theme theme={theme}>
+ <SortableTable
+ initialSort={[{sortKey: 'name', direction: 'ascending'}]}
+ onSortChange={onSortChange}
+ />
+ </Theme>,
+ );
+
+ const button = screen.getByRole('button', {name: 'Name'});
+ expect(button.querySelector('.astryx-icon')).toBeNull();
+ expect(screen.getByRole('columnheader', {name: 'Name'})).toHaveAttribute(
+ 'aria-sort',
+ 'ascending',
+ );
+ fireEvent.click(button);
+ expect(onSortChange).toHaveBeenCalledWith([
+ {sortKey: 'name', direction: 'descending'},
+ ]);
+ });
+
+ it('changes only the icon size for a size request', () => {
+ renderSorted({'table-sort-indicator': {size: 'sm'}});
+
+ const icon = screen
+ .getByRole('button', {name: 'Name'})
+ .querySelector('.astryx-icon');
+ expect(icon).toHaveAttribute('data-size', 'sm');
+ expect(glyph('Name')).toBe('arrowUp');
+ });
+});
diff --git a/packages/core/src/Table/plugins/sortable/useTableSortable.tsx b/packages/core/src/Table/plugins/sortable/useTableSortable.tsx
index 30c8695a1b..1a19609e05 100644
--- a/packages/core/src/Table/plugins/sortable/useTableSortable.tsx
+++ b/packages/core/src/Table/plugins/sortable/useTableSortable.tsx
@@ -4,7 +4,8 @@
/**
* @file useTableSortable.tsx
- * @input React, types, Icon, theme tokens, i18n (useComponentTranslator)
+ * @input React, types, Icon, the theme's `table-sort-indicator` icon slot,
+ * theme tokens, i18n (useComponentTranslator)
* @output Exports useTableSortable hook and sort-related types
* @position Sortable plugin; consumed by Table via plugins prop
*
@@ -18,6 +19,7 @@ import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars, radiusVars} from '../../../theme/tokens.stylex';
import {focusOutlineProps} from '../../../utils/focusOutline.stylex';
import {Icon} from '../../../Icon';
+import {ComponentIcon} from '../../../Icon/ComponentIcon';
import {resolveContextActions} from '../../tableContextMenu';
import type {
TablePlugin,
@@ -153,17 +155,22 @@ const sortStyles = stylex.create({
buttonAlignEnd: {
justifyContent: 'flex-end',
},
+ // The wrapper takes no block size, so a theme's larger glyph overflows it
+ // instead of growing the Sort control or the header row. When the slot
+ // hides the glyph, the empty wrapper collapses, so the button's gap does
+ // not offset an end-aligned label.
+ iconWrapper: {
+ display: {default: 'inline-flex', ':empty': 'none'},
+ alignItems: 'center',
+ blockSize: 0,
+ },
iconWrapperUnsorted: {
- display: 'inline-flex',
opacity: {
default: 0.35,
':is(th:hover *)': 1,
':focus-visible': 1,
},
},
- iconWrapperActive: {
- display: 'inline-flex',
- },
rank: {
fontSize: 10,
// eslint-disable-next-line @astryx/no-hardcoded-styles -- no token for lineHeight:1 (tight badge)
@@ -227,7 +234,7 @@ function SortHeaderButton<T extends Record<string, unknown>>({
config.isMultiSortEnabled === true && config.sort.length > 1;
const rank = isMultiSort && entryIndex >= 0 ? entryIndex + 1 : null;
- const iconName =
+ const indicator =
direction === 'ascending'
? 'arrowUp'
: direction === 'descending'
@@ -299,13 +306,13 @@ function SortHeaderButton<T extends Record<string, unknown>>({
<span>{children}</span>
<span
{...stylex.props(
- direction != null
- ? sortStyles.iconWrapperActive
- : sortStyles.iconWrapperUnsorted,
+ sortStyles.iconWrapper,
+ direction == null && sortStyles.iconWrapperUnsorted,
)}>
- <Icon
- icon={iconName}
- size="xsm"
+ <ComponentIcon
+ slot="table-sort-indicator"
+ state={{direction: direction ?? 'none'}}
+ fallback={{icon: indicator, size: 'xsm'}}
color={direction != null ? 'accent' : 'secondary'}
/>
</span>