Skip to content

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

TypeScript

feat(Table): make row expansion behave like its sibling plugins (#5995)

Ernest1a16c82e2280
diff --git a/.changeset/table-row-click-shared-guards.md b/.changeset/table-row-click-shared-guards.md
new file mode 100644
index 0000000000..471e366a3b
--- /dev/null
+++ b/.changeset/table-row-click-shared-guards.md
@@ -0,0 +1,17 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Whole-row-click expansion reuses the shared clickable-container guards instead of its own selector list. (#5995)
+@ernestt
+
+`useTableRowExpansion` and `useTableTreeData` each carried a hand-rolled copy of "did this click belong to something else" — the same nine selectors, written twice. `useClickableContainer` already owns that rule for every clickable surface in the system, and its `INTERACTIVE_SELECTORS` list is the fuller one: it also covers `role="link"`, `radio`, `switch`, `tab`, `menuitem`, `option`, `combobox`, `listbox`, `slider`, `spinbutton` and `[data-pressable-container]`, and it excludes `[aria-readonly="true"]`.
+
+Both plugins now call the hook's `hasInteractiveAncestor` and `hasTextSelection`, newly exported for containers that cannot use the hook itself — a `<tr>` assembled inside `transformBodyRow` has no ref to hand it.
+
+Two behaviour changes fall out of sharing, both fixes:
+
+- A click on a composed control the short list missed — a `role="tab"`, a segmented `role="radio"`, a `Slider` in a cell — no longer toggles the row underneath it.
+- The text-selection guard is scoped to the row instead of asking the document for any selection at all. Text selected elsewhere on the page no longer makes every row in the table inert.
+
+The walk also stops at the row rather than climbing to `document.body`, so an interactive ancestor of the whole table cannot suppress row clicks.
diff --git a/.changeset/table-row-expansion-chevron.md b/.changeset/table-row-expansion-chevron.md
new file mode 100644
index 0000000000..e8d331108f
--- /dev/null
+++ b/.changeset/table-row-expansion-chevron.md
@@ -0,0 +1,10 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Turn only the chevron glyph in `useTableRowExpansion`, not the button beneath it. (#5995)
+@ernestt
+
+The rotation was on the `<button>`, which is the hit target and carries the hover chip, so opening a row swung that rounded rectangle and its highlight a quarter turn along with the arrow — most visible mid-animation, where the chip passes through a diamond. A finished 90° turn on a 24px rounded square lands back on itself, which is why this only shows up in motion.
+
+The transform now sits on the glyph and the button stays put. The two transitions move onto `--duration-fast` and `--ease-standard` in the same pass, matching what `TableRow` already uses for its own hover transition.
diff --git a/.changeset/table-row-expansion-divider-placement.md b/.changeset/table-row-expansion-divider-placement.md
new file mode 100644
index 0000000000..74f624eb0c
--- /dev/null
+++ b/.changeset/table-row-expansion-divider-placement.md
@@ -0,0 +1,10 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Draw the row divider below a `useTableRowExpansion` detail panel rather than above it. (#5995)
+@ernestt
+
+An expanded row and its panel are one unit, but the divider was landing between them: the row drew its own bottom border, which put a line between the row and the detail it had just opened, and the panel drew none, so it ran flush into the next row. Both halves of that are backwards — the pair was split down the middle and then fused to the row below.
+
+The expanded row now gives up its border and the panel takes one. On a table with no row dividers the suppression removes a border that was never there and the panel's is never applied, so neither side has to consult the divider mode; only the panel does, to know whether to draw at all. The panel row carries `tableRowMarker`, which is how `TableCell` scopes its "no trailing line under the last row" rule, so an expanded last row still ends the table cleanly.
diff --git a/.changeset/table-row-expansion-panel-indent.md b/.changeset/table-row-expansion-panel-indent.md
new file mode 100644
index 0000000000..4ee24e2a86
--- /dev/null
+++ b/.changeset/table-row-expansion-panel-indent.md
@@ -0,0 +1,12 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Start the `useTableRowExpansion` detail panel at the first column rather than at the row edge. (#5995)
+@ernestt
+
+The panel is one cell spanning the whole row with a flat `20px` inline padding, so its content began under the chevron — a column to the left of every label it describes.
+
+It now indents by the chevron column's fixed width plus the inline padding a cell of that density gives its own content, read off the table context so it follows `density`, and written as a logical property so RTL mirrors it. It is not configurable: a panel starting anywhere else reads as a misalignment rather than as a choice.
+
+The chevron column's width cannot be a token reference — the layout does arithmetic on it — but it is the pixel value of `--spacing-10`, which is how the indent spells it. A test pins the two together so a change to the scale cannot silently unalign them.
diff --git a/.changeset/table-row-expansion-panel-variant.md b/.changeset/table-row-expansion-panel-variant.md
new file mode 100644
index 0000000000..8030afd7b6
--- /dev/null
+++ b/.changeset/table-row-expansion-panel-variant.md
@@ -0,0 +1,14 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `useTableRowExpansion` accepts `panelVariant`, and the detail panel now sits on the surface behind the table by default instead of on a wash of its own. (#5995)
+@ernestt
+
+The panel row painted `--color-background-muted` unconditionally, and being a `<tr>` the plugin builds itself, nothing a caller rendered could reach it.
+
+The panel is the row's continuation, not a surface of its own, so it now takes whatever the table sits on — the same thing the row does. That keeps the plugin unopinionated about the table's background: a table on a `Card` no longer stacks a third surface, and a striped table no longer paints a band in the same token as its own stripe, which read as a data row rather than as a detail.
+
+`panelVariant: 'muted'` keeps the wash for the case that wanted it — a bare table with no card, no dividers and no striping, where nothing else separates the panel from the data around it.
+
+**This changes the default appearance.** A table relying on the wash gets it back with `panelVariant: 'muted'`; in dark themes there is nothing to get back, because `--color-background-muted` is a low-alpha near-black that is close to invisible over a dark card — dark has effectively been rendering `transparent` all along.
diff --git a/.changeset/table-row-expansion-row-click.md b/.changeset/table-row-expansion-row-click.md
new file mode 100644
index 0000000000..bbe4f08817
--- /dev/null
+++ b/.changeset/table-row-expansion-row-click.md
@@ -0,0 +1,12 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `useTableRowExpansion` accepts `hasRowClickExpansion`, so a row opens when you click anywhere on it and not only on its chevron. (#5995)
+@ernestt
+
+`useTableTreeData` has had this since it shipped, under the same name and with the same behaviour. The detail-panel plugin is the other half of the same pair — one expands into child rows, one expands into a panel — and a caller who moved between them lost whole-row clicking without anything saying why. There was no way to add it back either: a click handler on the row has to know not to fire on a checkbox, a link or the end of a text drag, and none of that is reachable from the outside.
+
+Off by default, and pointer-only when on. The chevron button stays the accessible control, so keyboard and assistive-tech users are unaffected — this adds a shortcut for a mouse, not a second way to operate the table. Clicks that land on interactive cell content, clicks that end a text selection, and clicks on rows `getIsItemExpandable` has ruled out all pass through untouched. The chevron already stops propagation, so it does not toggle twice.
+
+Collapsed rows are wired up as well as expanded ones, which is most of the point: the row you want to click is the one that has not opened yet.
diff --git a/.changeset/table-striping-skips-expansion-panels.md b/.changeset/table-striping-skips-expansion-panels.md
new file mode 100644
index 0000000000..5551a06bf2
--- /dev/null
+++ b/.changeset/table-striping-skips-expansion-panels.md
@@ -0,0 +1,14 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Table` zebra striping counts data rows only, so expanding a row no longer inverts the stripe of every row below it. (#5995)
+@ernestt
+
+A row-expansion detail panel is appended as a sibling `<tr>` in the same `<tbody>`, and striping is `:nth-child(even)` — so the panel took a stripe turn of its own and pushed every row after it onto the opposite one. Opening a single row repainted half the table.
+
+The stripe now counts `:nth-child(even of :not([data-expansion-panel]))`. A panel is not a row and is not counted as one, so the data rows keep their parity whatever is open.
+
+`of S` has been Baseline since 2023, inside Astryx's support floor (AST-013). Below it the stripe rule is dropped rather than misapplied: an unstriped table, not a mis-striped one.
+
+Tables without the row-expansion plugin are unaffected — nothing else in the system emits `data-expansion-panel`.
diff --git a/packages/core/src/Table/TableRow.tsx b/packages/core/src/Table/TableRow.tsx
index 4dfb0bae31..124aebf5ff 100644
--- a/packages/core/src/Table/TableRow.tsx
+++ b/packages/core/src/Table/TableRow.tsx
@@ -42,18 +42,29 @@ export interface TableRowProps extends BaseProps<HTMLTableRowElement> {
isHeaderRow?: boolean;
}
+/**
+ * Zebra striping counts body rows — and a row-expansion panel is not one.
+ *
+ * The panel is appended as a sibling `<tr>` (see BaseTable's `afterRow`), so a
+ * plain `:nth-child(even)` counts it and every row below an open panel takes
+ * the opposite stripe: expanding one row repaints half the table. Counting
+ * `of :not([data-expansion-panel])` leaves the panel out of the sequence, so
+ * the rows keep their parity whatever is open.
+ */
+const NOT_PANEL_ROW = ':nth-child(even of :not([data-expansion-panel]))';
+
const stripedRowStyles = stylex.create({
row: {
backgroundColor: {
default: null,
- ':nth-child(even)': colorVars['--color-background-muted'],
+ [NOT_PANEL_ROW]: colorVars['--color-background-muted'],
},
// Publish the row's current overlay color as an inheritable variable so
// pinned/sticky cells (which paint an opaque background over the otherwise
// transparent row) can replay the exact same striping. Unset on odd rows.
'--table-row-overlay': {
default: null,
- ':nth-child(even)': colorVars['--color-background-muted'],
+ [NOT_PANEL_ROW]: colorVars['--color-background-muted'],
},
},
});
@@ -82,14 +93,14 @@ const stripedHoverRowStyles = stylex.create({
row: {
backgroundColor: {
default: null,
- ':nth-child(even)': colorVars['--color-background-muted'],
+ [NOT_PANEL_ROW]: colorVars['--color-background-muted'],
':hover:where(:not(:disabled,[aria-disabled="true"]))': {
'@media (hover: hover)': colorVars['--color-overlay-hover'],
},
},
'--table-row-overlay': {
default: null,
- ':nth-child(even)': colorVars['--color-background-muted'],
+ [NOT_PANEL_ROW]: colorVars['--color-background-muted'],
':hover:where(:not(:disabled,[aria-disabled="true"]))': {
'@media (hover: hover)': colorVars['--color-overlay-hover'],
},
diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
index a6f4befd9d..9c4928aac4 100644
--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx
@@ -6,6 +6,7 @@ import {useState} from 'react';
import {Table} from '../../Table';
import type {TableColumn} from '../../types';
import {useTableRowExpansion} from './useTableRowExpansion';
+import {spacingDefaults} from '../../../theme/tokens.stylex';
import {InternationalizationProvider} from '../../../i18n';
// popover mock for context-menu tests
@@ -58,10 +59,22 @@ function Harness({
initialExpanded = EMPTY_KEYS,
isItemExpandable,
renderExpanded = defaultRenderExpanded,
+ density,
+ hasRowClickExpansion,
+ columnsOverride,
+ panelVariant,
+ dividers,
+ isStriped,
}: {
initialExpanded?: Set<string>;
isItemExpandable?: (item: Row) => boolean;
renderExpanded?: (item: Row) => React.ReactNode;
+ density?: 'compact' | 'balanced' | 'spacious';
+ hasRowClickExpansion?: boolean;
+ columnsOverride?: TableColumn<Row>[];
+ panelVariant?: 'muted' | 'transparent';
+ dividers?: 'rows' | 'columns' | 'grid' | 'none';
+ isStriped?: boolean;
}) {
const [expandedKeys, setExpandedKeys] = useState(initialExpanded);
const expansion = useTableRowExpansion<Row>({
@@ -79,9 +92,19 @@ function Harness({
getRowKey: item => item.id,
renderExpanded,
getIsItemExpandable: isItemExpandable,
+ hasRowClickExpansion,
+ panelVariant,
});
return (
- <Table data={rows} columns={columns} idKey="id" plugins={{expansion}} />
+ <Table
+ data={rows}
+ columns={columnsOverride ?? columns}
+ idKey="id"
+ density={density}
+ dividers={dividers}
+ isStriped={isStriped}
+ plugins={{expansion}}
+ />
);
}
@@ -196,6 +219,280 @@ describe('useTableRowExpansion (detail panel)', () => {
).toBeGreaterThan(0);
});
+ it('turns the glyph without turning the button beneath it', () => {
+ // The button is the hit target and carries the hover chip. Rotating it
+ // swings that rounded rectangle around with the arrow, so the transform
+ // has to sit on the glyph instead.
+ render(<Harness initialExpanded={new Set(['a'])} />);
+ const button = screen.getAllByRole('button', {name: /collapse row/i})[0];
+ const glyph = button.querySelector('svg')?.parentElement;
+ expect(glyph).toHaveStyle({transform: 'rotate(90deg)'});
+ expect(button).not.toHaveStyle({transform: 'rotate(90deg)'});
+ });
+
+ it('starts the panel at the first column, not at the row edge', () => {
+ // Left to itself the panel begins under the chevron, a column to the left
+ // of every label it describes. It should start where the first column's
+ // content does: the chevron column's width plus a cell's own padding.
+ render(<Harness initialExpanded={new Set(['a'])} />);
+ expect(screen.getByTestId('panel').closest('td')).toHaveStyle({
+ paddingInlineStart: 'calc(var(--spacing-10) + var(--spacing-3))',
+ });
+ });
+
+ it('tracks the table density it is rendered at', () => {
+ render(<Harness initialExpanded={new Set(['a'])} density="spacious" />);
+ expect(screen.getByTestId('panel').closest('td')).toHaveStyle({
+ paddingInlineStart: 'calc(var(--spacing-10) + var(--spacing-4))',
+ });
+ });
+
+ it('sizes the chevron column at the spacing token the panel indents by', () => {
+ // The column width is a number the layout does arithmetic on, so it cannot
+ // be a token reference — but the panel's indent, which has to line up with
+ // the first column, spells it as `--spacing-10`. Pin the two together so a
+ // change to the scale cannot silently unalign them.
+ render(<Harness initialExpanded={new Set(['a'])} />);
+ const chevronHeader = screen.getAllByRole('columnheader')[0];
+ expect(chevronHeader).toHaveStyle({width: spacingDefaults['--spacing-10']});
+ });
+
+ describe('row divider placement', () => {
+ const panelCell = () =>
+ screen.getByTestId('panel').closest('td') as HTMLTableCellElement;
+ const cellsOf = (name: string) => [
+ ...(screen.getByText(name).closest('tr') as HTMLTableRowElement).cells,
+ ];
+
+ it('closes the pair below the panel rather than splitting it', () => {
+ // The row and its panel are one unit. A divider between them cuts the
+ // row off from the detail it opened, and leaves the panel running flush
+ // into the next row — the wrong way round on both counts.
+ render(<Harness initialExpanded={new Set(['a'])} />);
+ for (const cell of cellsOf('Ada')) {
+ expect(cell).toHaveStyle({borderBottomWidth: '0'});
+ }
+ expect(panelCell()).toHaveStyle({
+ borderBottomWidth: 'var(--border-width)',
+ });
+ });
+
+ it('leaves collapsed rows keeping their own divider', () => {
+ render(<Harness initialExpanded={new Set(['a'])} />);
+ for (const cell of cellsOf('Bo')) {
+ expect(cell).not.toHaveStyle({borderBottomWidth: '0'});
+ }
+ });
+
+ it('draws no panel divider on a table without row dividers', () => {
+ render(<Harness initialExpanded={new Set(['a'])} dividers="none" />);
+ expect(panelCell()).not.toHaveStyle({
+ borderBottomWidth: 'var(--border-width)',
+ });
+ });
+
+ it('draws the panel divider under grid dividers too', () => {
+ render(<Harness initialExpanded={new Set(['a'])} dividers="grid" />);
+ expect(panelCell()).toHaveStyle({
+ borderBottomWidth: 'var(--border-width)',
+ });
+ });
+ });
+
+ describe('panel variant', () => {
+ const panelRow = () =>
+ screen.getByTestId('panel').closest('tr') as HTMLTableRowElement;
+
+ it('leaves the panel on the surface behind the table by default', () => {
+ // The panel is the row's continuation, not a surface of its own: it
+ // takes whatever the table sits on, the way the row does.
+ render(<Harness initialExpanded={new Set(['a'])} />);
+ expect(panelRow()).not.toHaveStyle({
+ backgroundColor: 'var(--color-background-muted)',
+ });
+ });
+
+ it('washes the panel when muted is asked for', () => {
+ render(<Harness initialExpanded={new Set(['a'])} panelVariant="muted" />);
+ expect(panelRow()).toHaveStyle({
+ backgroundColor: 'var(--color-background-muted)',
+ });
+ });
+ });
+
+ describe('zebra striping', () => {
+ /**
+ * jsdom's selector engine does not implement `:nth-child(… of S)` — it
+ * matches nothing and reports no error — so the paint itself cannot be
+ * asserted here; the browser-side check is the visual regression suite.
+ * What this can pin is the two halves of the contract: the panel is a
+ * sibling row in the same tbody (which is what makes an exclusion
+ * necessary at all), and every stripe rule counts only rows that are not
+ * panels.
+ */
+ const stripeRules = () => {
+ const out: string[] = [];
+ for (const sheet of Array.from(document.styleSheets)) {
+ try {
+ for (const rule of Array.from(sheet.cssRules)) {
+ if (rule.cssText.includes(':nth-child(even')) {
+ out.push(rule.cssText);
+ }
+ }
+ } catch {
+ // cross-origin sheet; nothing of ours lives there
+ }
+ }
+ return out;
+ };
+
+ it('counts stripes over data rows only, so an open panel cannot flip them', () => {
+ render(<Harness isStriped initialExpanded={new Set(['a'])} />);
+
+ // The panel really is a row among the rows — left in the count, it takes
+ // the stripe meant for the row below it and inverts everything after.
+ const bodyRows = Array.from(
+ document.querySelectorAll<HTMLTableRowElement>('tbody > tr'),
+ );
+ expect(bodyRows).toHaveLength(4);
+ expect(bodyRows[1]).toHaveAttribute('data-expansion-panel');
+
+ const rules = stripeRules();
+ expect(rules.length).toBeGreaterThan(0);
+ for (const rule of rules) {
+ expect(rule).toContain('of :not([data-expansion-panel])');
+ }
+ });
+
+ it('marks the panel row so the stripe rule can skip it', () => {
+ // The attribute is what the selector keys off, so it is contract, not
+ // decoration — losing it silently restores the parity shift above.
+ render(<Harness initialExpanded={new Set(['a'])} isStriped />);
+ const panels = Array.from(
+ document.querySelectorAll<HTMLTableRowElement>('tbody tr'),
+ ).filter(r => r.hasAttribute('data-expansion-panel'));
+ expect(panels).toHaveLength(1);
+ expect(panels[0]).toHaveTextContent('Ada: Ada bio');
+ });
+ });
+
+ describe('whole-row-click expansion', () => {
+ const rowFor = (name: string) =>
+ screen.getByText(name).closest('tr') as HTMLTableRowElement;
+
+ it('leaves the row body inert by default', () => {
+ render(<Harness />);
+ fireEvent.click(screen.getByText('Ada'));
+ expect(screen.queryByTestId('panel')).not.toBeInTheDocument();
+ });
+
+ it('expands a collapsed row when its body is clicked', () => {
+ // The collapsed row is the one that has to respond: the early return
+ // that skips panel rendering must not skip the click handler with it.
+ render(<Harness hasRowClickExpansion />);
+ fireEvent.click(screen.getByText('Ada'));
+ expect(screen.getByTestId('panel')).toHaveTextContent('Ada: Ada bio');
+ });
+
+ it('collapses an expanded row when its body is clicked', () => {
+ render(<Harness hasRowClickExpansion initialExpanded={new Set(['a'])} />);
+ fireEvent.click(screen.getByText('Ada'));
+ expect(screen.queryByTestId('panel')).not.toBeInTheDocument();
+ });
+
+ it('does not double-toggle when the chevron itself is clicked', () => {
+ // The chevron stops propagation, so the row handler must not also fire —
+ // two toggles would land back where they started.
+ render(<Harness hasRowClickExpansion />);
+ fireEvent.click(screen.getAllByRole('button', {name: /expand row/i})[0]);
+ expect(screen.getByTestId('panel')).toBeInTheDocument();
+ });
+
+ it('yields to interactive cell content', () => {
+ // A composed link or action button does not stop propagation the way the
+ // chevron does, so the row handler has to check what was hit.
+ const onAction = vi.fn();
+ render(
+ <Harness
+ hasRowClickExpansion
+ columnsOverride={[
+ {
+ key: 'name',
+ header: 'Name',
+ renderCell: item => (
+ <button type="button" onClick={onAction}>
+ {`Act on ${item.name}`}
+ </button>
+ ),
+ },
+ ]}
+ />,
+ );
+ fireEvent.click(screen.getByText('Act on Ada'));
+ expect(onAction).toHaveBeenCalledTimes(1);
+ expect(screen.queryByTestId('panel')).not.toBeInTheDocument();
+ });
+
+ it('yields to a text selection', () => {
+ // Dragging across a cell to copy it ends in a click. Toggling then would
+ // shift the row out from under the text the reader just selected. The
+ // selection has to be anchored inside the row: one somewhere else on the
+ // page is not this row's business, which is why the shared guard scopes
+ // it to the node rather than asking the document for any selection.
+ render(<Harness hasRowClickExpansion />);
+ const cell = screen.getByText('Ada');
+ const selection = {
+ isCollapsed: false,
+ anchorNode: cell.firstChild ?? cell,
+ toString: () => 'Ada',
+ } as unknown as Selection;
+ const spy = vi.spyOn(document, 'getSelection').mockReturnValue(selection);
+ fireEvent.click(cell);
+ expect(screen.queryByTestId('panel')).not.toBeInTheDocument();
+ spy.mockRestore();
+ });
+
+ it('toggles despite a text selection somewhere else on the page', () => {
+ // The old guard asked the document for any selection at all, so text
+ // selected in a sidebar made every row in the table inert.
+ render(<Harness hasRowClickExpansion />);
+ const outside = document.createElement('p');
+ outside.textContent = 'elsewhere';
+ document.body.appendChild(outside);
+ const selection = {
+ isCollapsed: false,
+ anchorNode: outside.firstChild,
+ toString: () => 'elsewhere',
+ } as unknown as Selection;
+ const spy = vi.spyOn(document, 'getSelection').mockReturnValue(selection);
+ fireEvent.click(screen.getByText('Ada'));
+ expect(screen.getByTestId('panel')).toBeInTheDocument();
+ spy.mockRestore();
+ outside.remove();
+ });
+
+ it('leaves non-expandable rows inert', () => {
+ render(
+ <Harness
+ hasRowClickExpansion
+ isItemExpandable={item => item.id !== 'a'}
+ />,
+ );
+ fireEvent.click(screen.getByText('Ada'));
+ expect(screen.queryByTestId('panel')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByText('Bo'));
+ expect(screen.getByTestId('panel')).toHaveTextContent('Bo: Bo bio');
+ });
+
+ it('marks the row as interactive only when the click is wired up', () => {
+ const {unmount} = render(<Harness hasRowClickExpansion />);
+ expect(rowFor('Ada')).toHaveStyle({cursor: 'pointer'});
+ unmount();
+ render(<Harness />);
+ expect(rowFor('Ada')).not.toHaveStyle({cursor: 'pointer'});
+ });
+ });
+
it('localizes the chevron aria-label through the i18n catalog', () => {
render(
<InternationalizationProvider
diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
index 2e71a67112..53f6eb41a7 100644
--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
@@ -4,7 +4,8 @@
/**
* @file useTableRowExpansion.tsx
- * @input React, StyleX, Icon, Table types, i18n (useTranslator)
+ * @input React, StyleX, Icon, Table types, table context (density), i18n
+ * (useTranslator)
* @output Exports useTableRowExpansion hook + config type
* @position Row-expansion plugin (detail panel); consumed by Table via plugins prop
*
@@ -19,12 +20,25 @@
import {useMemo, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {spacingVars, colorVars, radiusVars} from '../../../theme/tokens.stylex';
+import {
+ spacingVars,
+ colorVars,
+ radiusVars,
+ borderVars,
+ durationVars,
+ easeVars,
+} from '../../../theme/tokens.stylex';
+import {tableRowMarker} from '../../table.stylex';
import {Icon} from '../../../Icon';
import {VisuallyHidden} from '../../../VisuallyHidden';
import {resolveContextActions} from '../../tableContextMenu';
+import {useTableContext} from '../../useTableCellStyles';
import {useTranslator} from '../../../i18n';
import {rtlStyles} from '../../../utils';
+import {
+ hasInteractiveAncestor,
+ hasTextSelection,
+} from '../../../hooks/useClickableContainer';
import type {
TablePlugin,
TableColumn,
@@ -60,13 +74,58 @@ export interface UseTableRowExpansionConfig<T extends Record<string, unknown>> {
* context-menu action, and never render a panel. @default all rows expandable
*/
getIsItemExpandable?: (item: T) => boolean;
+ /**
+ * Background behind the detail panel.
+ *
+ * - `transparent` (default): the panel paints nothing and takes whatever
+ * surface is behind the table. The panel is the row's own continuation,
+ * so it inherits the table's background the way the row does, and on a
+ * striped table the zebra reads on unchanged — a panel is not a row, and
+ * is not counted as one.
+ * - `muted`: a wash marking the panel as commentary on the row above rather
+ * than another row of data. Reach for it in a bare table — no card, no
+ * dividers, no striping — where nothing else distinguishes the panel from
+ * the data around it. It is an opt-in, not the house style: a table on a
+ * Card gets a third surface out of it, and a striped table gets a band in
+ * the same token as the stripe, which reads as a data row.
+ *
+ * Worth knowing when choosing: the wash is a low-alpha near-black, so over a
+ * dark card it is close to invisible. `muted` is largely a light-theme
+ * effect, and dark themes look like `transparent` either way.
+ * @default 'transparent'
+ */
+ panelVariant?: 'muted' | 'transparent';
+ /**
+ * Toggle a row by clicking anywhere on it, not only on its chevron.
+ *
+ * This is a pointer-only convenience layered over the chevron: keyboard and
+ * assistive-tech users toggle via the chevron button (which stays the
+ * accessible control). Clicks originating from interactive cell content
+ * (buttons, links, form controls) or a text selection do not toggle.
+ * Non-expandable rows stay inert.
+ * @default false (only the chevron toggles expansion).
+ */
+ hasRowClickExpansion?: boolean;
}
// =============================================================================
// Styles
// =============================================================================
-const EXPANSION_COLUMN_WIDTH = {type: 'pixel' as const, value: 40};
+/**
+ * The chevron column's width, in pixels.
+ *
+ * A column width is a number the layout does arithmetic on, not a CSS value,
+ * so this cannot be a token reference — but it is the pixel value of
+ * `--spacing-10`, and the panel's indent (which has to line up with the first
+ * real column) spells it as the token. The unit test pins the two together so
+ * a change to the scale cannot silently unalign them.
+ */
+const EXPANSION_COLUMN_WIDTH_PX = 40;
+const EXPANSION_COLUMN_WIDTH = {
+ type: 'pixel' as const,
+ value: EXPANSION_COLUMN_WIDTH_PX,
+};
const expansionStyles = stylex.create({
chevronButton: {
@@ -84,8 +143,12 @@ const expansionStyles = stylex.create({
':is(:disabled,[aria-disabled="true"])': 'default',
},
color: colorVars['--color-icon-secondary'],
- transitionProperty: 'transform, color',
- transitionDuration: '150ms',
+ // Colour only. The rotation belongs to the glyph, not to the button: the
+ // button is the hit target and carries the hover chip, and turning that
+ // swings the rounded rectangle and its highlight around with the arrow.
+ transitionProperty: 'color',
+ transitionDuration: durationVars['--duration-fast'],
+ transitionTimingFunction: easeVars['--ease-standard'],
padding: 0,
// Match IconButton ghost hover: subtle overlay background.
backgroundImage: {
@@ -98,6 +161,11 @@ const expansionStyles = stylex.create({
color: colorVars['--color-icon-primary'],
},
},
+ chevron: {
+ transitionProperty: 'transform',
+ transitionDuration: durationVars['--duration-fast'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ },
// The RTL mirror is folded into each state's transform rather than living
// on a parent span, matching TreeListItem's chevron (both are `transform`,
// so on one element the later value would win).
@@ -118,7 +186,65 @@ const expansionStyles = stylex.create({
},
expandedCell: {
paddingBlock: spacingVars['--spacing-4'],
- paddingInline: spacingVars['--spacing-5'],
+ paddingInlineEnd: spacingVars['--spacing-5'],
+ },
+ /** Whole-row-click expansion: signal the row is interactive. */
+ clickableRow: {
+ cursor: {
+ default: 'pointer',
+ ':is(:disabled,[aria-disabled="true"])': 'default',
+ },
+ },
+});
+
+/**
+ * An expanded row and its panel are one unit, so the row divider belongs after
+ * the pair rather than between them — left alone, the row's own bottom border
+ * draws a line cutting it off from the detail it just opened, and the panel
+ * then runs flush into the next row, which is the wrong way round.
+ *
+ * So the row gives up its border and the panel takes one. On a table with no
+ * row dividers the suppression is a no-op (there was no border to remove) and
+ * the panel's is never applied, so neither needs to consult the divider mode.
+ */
+const dividerStyles = stylex.create({
+ expandedRowCell: {
+ borderBottomWidth: 0,
+ },
+ panelCell: {
+ borderBottomWidth: {
+ default: borderVars['--border-width'],
+ // Same rule TableCell uses: no trailing line under the last row of the
+ // table. Scoped to the marker so <tbody>, also a :last-child, does not
+ // match and suppress every panel's border.
+ [stylex.when.ancestor(':last-child', tableRowMarker)]: '0',
+ },
+ borderBottomStyle: 'solid',
+ borderBottomColor: colorVars['--color-border'],
+ },
+});
+
+/**
+ * Start inset for the detail panel, one per density.
+ *
+ * The panel is one cell spanning the whole row, so left to itself its content
+ * starts at the row's edge — under the chevron, a column to the left of every
+ * label it describes. These line it up with the first real column instead: the
+ * chevron column's fixed width, plus the inline padding a cell of that density
+ * gives its own content.
+ *
+ * Written as a logical property so RTL mirrors it, and kept in `calc` so the
+ * padding half still tracks the spacing scale.
+ */
+const panelIndentStyles = stylex.create({
+ compact: {
+ paddingInlineStart: `calc(${spacingVars['--spacing-10']} + ${spacingVars['--spacing-2']})`,
+ },
+ balanced: {
+ paddingInlineStart: `calc(${spacingVars['--spacing-10']} + ${spacingVars['--spacing-3']})`,
+ },
+ spacious: {
+ paddingInlineStart: `calc(${spacingVars['--spacing-10']} + ${spacingVars['--spacing-4']})`,
},
});
@@ -137,12 +263,7 @@ function ExpansionChevron({
return (
<button
type="button"
- {...stylex.props(
- expansionStyles.chevronButton,
- isExpanded
- ? expansionStyles.chevronExpanded
- : expansionStyles.chevronCollapsed,
- )}
+ {...stylex.props(expansionStyles.chevronButton)}
onClick={e => {
e.stopPropagation();
onToggle();
@@ -153,11 +274,49 @@ function ExpansionChevron({
: t('@astryx.tableRowExpansion.expandRow')
}
aria-expanded={isExpanded}>
- <Icon icon="chevronRight" size="xsm" />
+ <Icon
+ icon="chevronRight"
+ size="xsm"
+ xstyle={[
+ expansionStyles.chevron,
+ isExpanded
+ ? expansionStyles.chevronExpanded
+ : expansionStyles.chevronCollapsed,
+ ]}
+ />
</button>
);
}
+/**
+ * The detail panel's cell. A component rather than a bare `<td>` so it can
+ * read the table's density and divider mode off the context — to indent itself
+ * to match the first column, and to carry the row divider its own row gave up.
+ * The plugin builds this row outside the Table's own render, where that
+ * context is not otherwise in hand.
+ */
+function ExpansionPanelCell({
+ colSpan,
+ children,
+}: {
+ colSpan: number;
+ children: ReactNode;
+}) {
+ const ctx = useTableContext();
+ const hasRowDividers = ctx?.dividers === 'rows' || ctx?.dividers === 'grid';
+ return (
+ <td
+ colSpan={colSpan}
+ {...stylex.props(
+ expansionStyles.expandedCell,
+ panelIndentStyles[ctx?.density ?? 'balanced'],
+ hasRowDividers && dividerStyles.panelCell,
+ )}>
+ {children}
+ </td>
+ );
+}
+
// =============================================================================
// Hook
// =============================================================================
@@ -198,6 +357,8 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
getRowKey,
renderExpanded,
getIsItemExpandable,
+ hasRowClickExpansion,
+ panelVariant = 'transparent',
} = config;
const t = useTranslator();
@@ -262,6 +423,11 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
const isExpanded = expandedKeys.has(key);
return {
...props,
+ // Hand the row divider to the panel below, so the line closes the
+ // row-plus-panel pair instead of splitting it.
+ xstyle: isExpanded
+ ? [...props.xstyle, dividerStyles.expandedRowCell]
+ : props.xstyle,
contextMenuActions: () => [
...resolveContextActions(props.contextMenuActions),
{
@@ -294,27 +460,72 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
return props;
}
const key = getRowKey(item);
+
+ // Whole-row-click expansion (opt-in), applied before the collapsed
+ // early-return: a collapsed row is precisely the one a click has to
+ // reach, since opening it is the whole point.
+ const withClick = hasRowClickExpansion
+ ? {
+ ...props,
+ htmlProps: {
+ ...props.htmlProps,
+ onClick: (event: React.MouseEvent<HTMLTableRowElement>) => {
+ // Don't hijack clicks on interactive cell content (the
+ // chevron already stops propagation, but a composed
+ // selection checkbox, link, or action button does not) or a
+ // text selection. Both rules come from
+ // `useClickableContainer`, the same pair every clickable
+ // surface in the system uses — the hook itself wants a ref
+ // we have no way to hand it from inside `transformBodyRow`,
+ // so this shares its guards rather than its plumbing.
+ const row = event.currentTarget;
+ const target = event.target;
+ if (!(target instanceof Element)) {
+ return;
+ }
+ if (target !== row && hasInteractiveAncestor(target, row)) {
+ return;
+ }
+ if (hasTextSelection(row)) {
+ return;
+ }
+ props.htmlProps.onClick?.(event);
+ onToggle(key);
+ },
+ },
+ xstyle: [...props.xstyle, expansionStyles.clickableRow],
+ }
+ : props;
+
if (!expandedKeys.has(key)) {
- return props;
+ return withClick;
}
const panel = (
<tr
key={`${key}-expanded`}
- {...stylex.props(expansionStyles.expandedRow)}>
- <td
- colSpan={columnCountRef.current}
- {...stylex.props(expansionStyles.expandedCell)}>
+ // A panel is its row's continuation, not a row of its own. Striping
+ // counts `:nth-child(even of :not([data-expansion-panel]))`, so this
+ // attribute is what keeps an open panel from inverting the zebra of
+ // every row beneath it. Load-bearing, not diagnostic.
+ data-expansion-panel=""
+ {...stylex.props(
+ // Carries the marker so the panel cell's divider can ask whether
+ // this row is the table's last, the same way TableCell does.
+ tableRowMarker,
+ panelVariant === 'muted' && expansionStyles.expandedRow,
+ )}>
+ <ExpansionPanelCell colSpan={columnCountRef.current}>
{renderExpanded(item)}
- </td>
+ </ExpansionPanelCell>
</tr>
);
return {
- ...props,
- afterRow: props.afterRow ? (
+ ...withClick,
+ afterRow: withClick.afterRow ? (
<>
- {props.afterRow}
+ {withClick.afterRow}
{panel}
</>
) : (
@@ -328,6 +539,8 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
getRowKey,
renderExpanded,
getIsItemExpandable,
+ hasRowClickExpansion,
+ panelVariant,
onToggle,
t,
expansionColumn,
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
index f7eb1236c9..3612b8786b 100644
--- a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
@@ -43,6 +43,10 @@ import * as stylex from '@stylexjs/stylex';
import {colorVars, radiusVars, spacingVars} from '../../../theme/tokens.stylex';
import {Icon} from '../../../Icon';
import {mergeRefs} from '../../../utils';
+import {
+ hasInteractiveAncestor,
+ hasTextSelection,
+} from '../../../hooks/useClickableContainer';
import type {
TablePlugin,
TableColumn,
@@ -682,16 +686,19 @@ export function useTableTreeData<T extends Record<string, unknown>>(
onClick: (event: React.MouseEvent<HTMLTableRowElement>) => {
// Don't hijack clicks on interactive cell content (the chevron
// already stops propagation, but a composed selection checkbox,
- // link, or action button does not) or a text selection.
- const target = event.target as HTMLElement;
- if (
- target.closest(
- 'button, a, input, select, textarea, [role="button"], [role="checkbox"], [contenteditable="true"]',
- )
- ) {
+ // link, or action button does not) or a text selection. Shared
+ // with `useClickableContainer` and the row-expansion plugin, so
+ // the three surfaces cannot drift apart on what counts as
+ // "this click belongs to something else".
+ const row = event.currentTarget;
+ const target = event.target;
+ if (!(target instanceof Element)) {
+ return;
+ }
+ if (target !== row && hasInteractiveAncestor(target, row)) {
return;
}
- if ((window.getSelection()?.toString() ?? '') !== '') {
+ if (hasTextSelection(row)) {
return;
}
cfg.onToggleItem(item);
diff --git a/packages/core/src/Table/useTableRowExpansion.doc.mjs b/packages/core/src/Table/useTableRowExpansion.doc.mjs
index f92ab6e8f8..217eef486c 100644
--- a/packages/core/src/Table/useTableRowExpansion.doc.mjs
+++ b/packages/core/src/Table/useTableRowExpansion.doc.mjs
@@ -7,7 +7,7 @@ export const docs = {
subComponentOf: 'Table',
displayName: 'useTableRowExpansion',
description:
- 'Hook that returns a TablePlugin which expands a full-width detail panel below a row, rendered by the consumer via renderExpanded(item). Adds a leading chevron column and a right-click "Expand/Collapse row" action; the consumer owns the expandedKeys set. Use it for master-detail rows (order details, forms, charts, nested tables). For hierarchical data where child rows reuse the parent columns, use useTableTreeData + useTableTreeState instead.',
+ 'Hook that returns a TablePlugin which expands a full-width detail panel below a row, rendered by the consumer via renderExpanded(item). Adds a leading chevron column and a right-click "Expand/Collapse row" action; the consumer owns the expandedKeys set. The panel spans the row but starts its content at the first column, past the chevron, so detail lines up with the labels above it; the inset follows the table density. Use it for master-detail rows (order details, forms, charts, nested tables). For hierarchical data where child rows reuse the parent columns, use useTableTreeData + useTableTreeState instead.',
props: [
{
name: 'expandedKeys',
@@ -41,6 +41,20 @@ export const docs = {
description:
'Control which rows are expandable. Non-expandable rows show no chevron, no context-menu action, and never render a panel. Defaults to all rows expandable.',
},
+ {
+ name: 'panelVariant',
+ type: "'muted' | 'transparent'",
+ description:
+ "Background behind the detail panel. 'transparent' (default) paints nothing: the panel is the row's continuation and takes whatever surface the table sits on, so a Card shows through and a striped table's zebra reads on unchanged. 'muted' washes it, marking it as commentary rather than another row of data — reach for it in a bare table with no card, dividers or striping, where nothing else makes that distinction. The wash is a low-alpha near-black, so it is close to invisible over a dark card: 'muted' is largely a light-theme effect.",
+ default: "'transparent'",
+ },
+ {
+ name: 'hasRowClickExpansion',
+ type: 'boolean',
+ description:
+ 'Toggle a row by clicking anywhere on it, not only on its chevron. A pointer-only convenience layered over the chevron, which stays the accessible control for keyboard and assistive tech. Clicks on interactive cell content (buttons, links, form controls) or on a text selection do not toggle, and non-expandable rows stay inert.',
+ default: 'false',
+ },
],
examples: [
{
@@ -97,7 +111,7 @@ const tree = useTableTreeData({
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
description:
- 'Returns a TablePlugin that expands a full-width detail panel below a row via renderExpanded(item). Adds a chevron column + right-click expand/collapse action; consumer owns expandedKeys. For nested child rows that reuse parent columns, use useTableTreeData + useTableTreeState instead.',
+ 'Returns a TablePlugin that expands a full-width detail panel below a row via renderExpanded(item). Adds a chevron column + right-click expand/collapse action; consumer owns expandedKeys. Panel content starts at the first column (past the chevron), inset by density. For nested child rows that reuse parent columns, use useTableTreeData + useTableTreeState instead.',
propDescriptions: {
expandedKeys: 'Set of currently-expanded row keys. Consumer-owned.',
onToggle: 'Called with a row key when its expansion is toggled.',
@@ -106,5 +120,9 @@ export const docsDense = {
'Render the full-width detail panel below an expanded row. Receives the row item.',
getIsItemExpandable:
'Control which rows are expandable. Defaults to all rows expandable.',
+ panelVariant:
+ "Detail panel background: 'transparent' (default) paints nothing, so the panel takes the surface behind the table and leaves a striped table's zebra alone; 'muted' washes it, for a bare table where nothing else separates the panel from the data.",
+ hasRowClickExpansion:
+ 'Toggle a row by clicking anywhere on it, not just the chevron; pointer-only, skips interactive cell content and text selections. Defaults to false.',
},
};
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index 8b5ec922fe..f465e2a473 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -100,6 +100,8 @@ export type {ImageSampleRegion, UseImageModeOptions} from './useImageMode';
export {
useClickableContainer,
INTERACTIVE_SELECTORS,
+ hasInteractiveAncestor,
+ hasTextSelection,
} from './useClickableContainer';
export type {
UseClickableContainerOptions,
diff --git a/packages/core/src/hooks/useClickableContainer.ts b/packages/core/src/hooks/useClickableContainer.ts
index 7e5071133a..35985f1c7a 100644
--- a/packages/core/src/hooks/useClickableContainer.ts
+++ b/packages/core/src/hooks/useClickableContainer.ts
@@ -61,8 +61,14 @@ const NON_INTERACTIVE_SELECTORS = '[aria-readonly="true"]';
* Check whether an element has an interactive ancestor between it and the root.
* If the click target is inside a nested button/link/etc., we should NOT
* handle it at the container level.
+ *
+ * Exported for containers that cannot use the hook itself — a `<tr>` whose
+ * props are assembled inside a Table plugin's `transformBodyRow`, for
+ * instance, has no ref to hand the hook but needs the identical rule. Sharing
+ * the walk keeps one definition of "this click belongs to something else"
+ * instead of a short hand-rolled selector list per caller.
*/
-function hasInteractiveAncestor(el: Element, rootEl: Element): boolean {
+export function hasInteractiveAncestor(el: Element, rootEl: Element): boolean {
let current: Element | null = el;
while (current != null && current !== rootEl && current !== document.body) {
if (
@@ -76,8 +82,15 @@ function hasInteractiveAncestor(el: Element, rootEl: Element): boolean {
return false;
}
-/** Check if there's a text selection inside the node (don't navigate on text select) */
-function hasTextSelection(node: Element): boolean {
+/**
+ * Check if there's a text selection inside the node (don't navigate on text select)
+ *
+ * Exported alongside {@link hasInteractiveAncestor} for the same reason: a
+ * click that ends a text drag is not a click on the container, and every
+ * clickable surface needs that rule, hook or no hook. Scoped to the node, so a
+ * selection somewhere else on the page does not make the surface inert.
+ */
+export function hasTextSelection(node: Element): boolean {
if (typeof document === 'undefined' || !('getSelection' in document)) {
return false;
}