Skip to content

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

TypeScript

feat(Table): let useTableSelection opt out of the checked-row highlight (#5310)

Ernest4e5f148e8ccc
diff --git a/.changeset/table-selection-row-highlight-opt-out.md b/.changeset/table-selection-row-highlight-opt-out.md
new file mode 100644
index 0000000000..e364016440
--- /dev/null
+++ b/.changeset/table-selection-row-highlight-opt-out.md
@@ -0,0 +1,21 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Table: let `useTableSelection` opt out of the checked-row accent wash
+
+The selection plugin paints checked rows by writing `backgroundColor` straight
+onto each `<tr>` from its row ref callback. An inline style outranks anything
+StyleX can layer on, so a product that wanted the row background for its own
+meaning had no way to reclaim it short of forking the plugin.
+
+`hasRowHighlight` turns the wash off. It defaults to `true`, so existing tables
+are untouched. Only the background is dropped — `aria-selected` is still set and
+removed exactly as before, since that is the half of the state screen readers
+read.
+
+```tsx
+useTableSelection({...config, hasRowHighlight: false});
+```
+
+@ernestt
diff --git a/packages/core/src/Table/plugins/selection/useTableSelection.test.tsx b/packages/core/src/Table/plugins/selection/useTableSelection.test.tsx
index 3b39cbd875..fef04d2828 100644
--- a/packages/core/src/Table/plugins/selection/useTableSelection.test.tsx
+++ b/packages/core/src/Table/plugins/selection/useTableSelection.test.tsx
@@ -13,6 +13,7 @@ import {act, render, renderHook, screen, within} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Table} from '../../Table';
import {useTableSelection} from './useTableSelection';
+import {colorVars} from '../../../theme/tokens.stylex';
import type {BodyRowRenderProps, TableColumn} from '../../types';
// =============================================================================
@@ -41,10 +42,12 @@ function SelectionTable({
getIsItemSelectable,
getIsItemEnabled,
getRowLabel,
+ hasRowHighlight,
}: {
getIsItemSelectable?: (item: SelectableUser) => boolean;
getIsItemEnabled?: (item: SelectableUser) => boolean;
getRowLabel?: (item: SelectableUser) => string;
+ hasRowHighlight?: boolean;
}) {
const [selectedKeys, setSelectedKeys] = useState<Set<string>>(new Set());
@@ -78,6 +81,7 @@ function SelectionTable({
getIsItemSelectable,
getIsItemEnabled,
getRowLabel,
+ hasRowHighlight,
});
return (
@@ -211,6 +215,78 @@ describe('useTableSelection', () => {
expect(headers).toHaveLength(3);
});
+ describe('hasRowHighlight', () => {
+ const selectedBgColor = colorVars['--color-accent-muted'];
+
+ it('paints a checked row with the accent wash by default', async () => {
+ const user = userEvent.setup();
+ render(<SelectionTable />);
+
+ await user.click(screen.getAllByLabelText('Select row')[0]);
+
+ const row = screen.getAllByRole('row')[1];
+ expect(row.style.backgroundColor).toBe(selectedBgColor);
+ expect(row).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('leaves the row background alone when hasRowHighlight is false', async () => {
+ const user = userEvent.setup();
+ render(<SelectionTable hasRowHighlight={false} />);
+
+ await user.click(screen.getAllByLabelText('Select row')[0]);
+
+ const row = screen.getAllByRole('row')[1];
+ expect(row.style.backgroundColor).toBe('');
+ // The wash is opt-out; the semantics are not.
+ expect(row).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('clears an already-painted row when the flag flips to false', async () => {
+ const user = userEvent.setup();
+ const {rerender} = render(<SelectionTable />);
+
+ await user.click(screen.getAllByLabelText('Select row')[0]);
+ expect(screen.getAllByRole('row')[1].style.backgroundColor).toBe(
+ selectedBgColor,
+ );
+
+ rerender(<SelectionTable hasRowHighlight={false} />);
+
+ const row = screen.getAllByRole('row')[1];
+ expect(row.style.backgroundColor).toBe('');
+ expect(row).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('repaints an already-checked row when the flag flips back to true', async () => {
+ const user = userEvent.setup();
+ const {rerender} = render(<SelectionTable hasRowHighlight={false} />);
+
+ await user.click(screen.getAllByLabelText('Select row')[0]);
+ rerender(<SelectionTable hasRowHighlight />);
+
+ expect(screen.getAllByRole('row')[1].style.backgroundColor).toBe(
+ selectedBgColor,
+ );
+ });
+
+ it('never paints unchecked rows in either mode', async () => {
+ const user = userEvent.setup();
+ const {rerender} = render(<SelectionTable />);
+
+ await user.click(screen.getAllByLabelText('Select row')[0]);
+ expect(screen.getAllByRole('row')[2].style.backgroundColor).toBe('');
+ expect(screen.getAllByRole('row')[2]).not.toHaveAttribute(
+ 'aria-selected',
+ );
+
+ rerender(<SelectionTable hasRowHighlight={false} />);
+ expect(screen.getAllByRole('row')[2].style.backgroundColor).toBe('');
+ expect(screen.getAllByRole('row')[2]).not.toHaveAttribute(
+ 'aria-selected',
+ );
+ });
+ });
+
it('unsubscribes detached row refs instead of accumulating listeners', () => {
const getIsItemSelected = vi.fn(() => false);
const {result, rerender} = renderHook(() =>
diff --git a/packages/core/src/Table/plugins/selection/useTableSelection.tsx b/packages/core/src/Table/plugins/selection/useTableSelection.tsx
index 880e5db139..178b35403e 100644
--- a/packages/core/src/Table/plugins/selection/useTableSelection.tsx
+++ b/packages/core/src/Table/plugins/selection/useTableSelection.tsx
@@ -26,7 +26,13 @@
* DOM elements and no central element tracking. Each subscription
* self-cleans when the row disconnects.
*
+ * Because the background is an inline style, it outranks anything
+ * userland can layer on with StyleX. `hasRowHighlight: false` is the
+ * supported way to reclaim the row background; `aria-selected` is
+ * unaffected by it.
+ *
* SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Table/useTableSelection.doc.mjs (config prop table)
* - /packages/core/src/Table/Table.doc.mjs (selection documentation)
* - /packages/core/src/Table/index.ts (exports)
*/
@@ -81,6 +87,22 @@ export interface UseTableSelectionConfig<T extends Record<string, unknown>> {
* ```
*/
getRowLabel?: (item: T) => string;
+ /**
+ * Paint checked rows with the accent wash. Set false when the surrounding
+ * UI already uses row background to mean something else — a row that is
+ * open in a detail panel, for instance. The wash is an inline style, so
+ * it cannot be overridden from userland; this flag is the way off it.
+ *
+ * Only the background is dropped. `aria-selected` is still set on checked
+ * rows either way, so the selection stays legible to screen readers.
+ *
+ * @default true
+ * @example
+ * ```
+ * useTableSelection({...config, hasRowHighlight: false})
+ * ```
+ */
+ hasRowHighlight?: boolean;
}
// =============================================================================
@@ -121,18 +143,24 @@ function createSelectionStore<T extends Record<string, unknown>>(
/**
* Apply or remove selection styling on a <tr> element.
+ *
+ * `aria-selected` tracks selection on its own: it is the semantic half of
+ * the state and stays correct whether or not the row is painted.
*/
function applyRowSelectionStyle(
el: HTMLTableRowElement,
isSelected: boolean,
+ hasRowHighlight: boolean,
): void {
if (isSelected) {
el.setAttribute('aria-selected', 'true');
- el.style.backgroundColor = selectedBgColor;
} else {
el.removeAttribute('aria-selected');
- el.style.backgroundColor = '';
}
+ // Written on every pass, not just when painting: the flag can flip while a
+ // row is already selected, and the wash has to come back off.
+ el.style.backgroundColor =
+ isSelected && hasRowHighlight ? selectedBgColor : '';
}
// =============================================================================
@@ -358,18 +386,23 @@ export function useTableSelection<T extends Record<string, unknown>>(
if (!el) {
return;
}
+ const applyStyle = () => {
+ const config = store.getConfig();
+ applyRowSelectionStyle(
+ el,
+ config.getIsItemSelected(item),
+ config.hasRowHighlight ?? true,
+ );
+ };
// Apply initial style
- applyRowSelectionStyle(el, store.getConfig().getIsItemSelected(item));
+ applyStyle();
// Subscribe for future changes
const unsub = store.subscribe(() => {
if (!el.isConnected) {
unsub();
return;
}
- applyRowSelectionStyle(
- el,
- store.getConfig().getIsItemSelected(item),
- );
+ applyStyle();
});
return () => {
unsub();
diff --git a/packages/core/src/Table/useTableSelection.doc.mjs b/packages/core/src/Table/useTableSelection.doc.mjs
index 012f134a7d..5a445dccb6 100644
--- a/packages/core/src/Table/useTableSelection.doc.mjs
+++ b/packages/core/src/Table/useTableSelection.doc.mjs
@@ -61,6 +61,13 @@ export const docs = {
description:
'Derives a human-readable identity for a row; the row checkbox\'s hidden label becomes `Select ${getRowLabel(item)}` so screen readers announce which row each checkbox selects. Falls back to "Select row" when omitted.',
},
+ {
+ name: 'hasRowHighlight',
+ type: 'boolean',
+ description:
+ 'Paints checked rows with the accent wash. Set false when the surrounding UI already uses row background to mean something else (a row open in a detail panel, say) — the wash is an inline style, so it cannot be overridden from userland. Only the background is dropped: aria-selected is still set on checked rows either way.',
+ default: 'true',
+ },
],
examples: [
{
@@ -82,6 +89,21 @@ const selectionPlugin = useTableSelection({
idKey="id"
plugins={{selection: selectionPlugin}}
/>;
+`,
+ },
+ {
+ label: 'Opt out of the checked-row wash',
+ code: `
+// This table already uses row background to mean "open in the detail
+// panel". Turning the selection wash off keeps that meaning unambiguous;
+// the checkbox and aria-selected still carry the selection.
+const selectionPlugin = useTableSelection({
+ getIsItemSelected: item => selectedIds.has(item.id),
+ onSelectItem: ({item, isSelected}) => toggle(item.id, isSelected),
+ onSelectAll: ({isAllSelected}) => selectAll(isAllSelected),
+ getIsAllSelected: () => selectedIds.size === users.length,
+ hasRowHighlight: false,
+});
`,
},
],
@@ -142,6 +164,13 @@ export const docsZh = {
description:
'为行派生人类可读的标识;行复选框的隐藏标签变为 `Select ${getRowLabel(item)}`,让屏幕阅读器播报每个复选框选择的是哪一行。省略时回退为 "Select row"。',
},
+ {
+ name: 'hasRowHighlight',
+ type: 'boolean',
+ description:
+ '为选中的行绘制强调色背景。当周围的界面已用行背景表达其他含义(例如该行已在详情面板中打开)时设为 false —— 该背景是内联样式,无法从业务代码覆盖。仅去掉背景:无论如何选中的行仍会设置 aria-selected。',
+ default: 'true',
+ },
],
};
@@ -164,5 +193,7 @@ export const docsDense = {
'Returns whether row checkbox is interactive; disabled rows show disabled checkbox.',
getRowLabel:
'Derives row identity for the checkbox\'s hidden label: `Select ${getRowLabel(item)}`. Falls back to "Select row" when omitted.',
+ hasRowHighlight:
+ 'false => skip the accent wash on checked rows (inline style, not overridable from userland). aria-selected is unaffected. Defaults to true.',
},
};