Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type { Action } from '../ds-table.types';
import { columns, defaultData, type Person } from '../stories/common/story-data';

describe('DsTable - Row Actions', () => {
it('should render reorderable table with order column', async () => {
it('should reorder rows when dragging the handle past the next row', async () => {
const onOrderChange = vi.fn();
const fiveItems = defaultData.slice(0, 5);

Expand All @@ -14,12 +14,50 @@ describe('DsTable - Row Actions', () => {
);

const dataRows = page.getByRole('row').all().slice(1);

expect(dataRows).toHaveLength(5);

await expect.element(page.getByText('Order')).toBeVisible();
await expect.element(page.getByRole('row').nth(1)).toHaveTextContent('Tanner');
await expect.element(page.getByRole('row').nth(2)).toHaveTextContent('Kevin');

const handle = page.getByRole('row').nth(1).getByRole('button').element() as HTMLElement;
const kevinRow = page.getByRole('row').nth(2).element() as HTMLTableRowElement;

const handleRect = handle.getBoundingClientRect();
const kevinRect = kevinRow.getBoundingClientRect();
const startX = handleRect.left + handleRect.width / 2;
const startY = handleRect.top + handleRect.height / 2;
const endY = kevinRect.top + kevinRect.height / 2 + 5;

// dnd-kit's MouseSensor measures droppable rects on requestAnimationFrame
// after activation, and the resulting state update schedules another render.
// Yielding a few frames between events lets collision detection see the row
// rects before each drag move runs.
const settle = async () => {
for (let i = 0; i < 3; i += 1) {
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
}
};

handle.dispatchEvent(
new MouseEvent('mousedown', { clientX: startX, clientY: startY, button: 0, bubbles: true }),
);
await settle();

document.dispatchEvent(new MouseEvent('mousemove', { clientX: startX, clientY: endY, bubbles: true }));
await settle();

document.dispatchEvent(new MouseEvent('mouseup', { clientX: startX, clientY: endY, bubbles: true }));

await vi.waitFor(() => {
expect(onOrderChange).toHaveBeenCalledTimes(1);
});

const newOrder = onOrderChange.mock.calls[0]?.[0] as Person[] | undefined;
expect(newOrder?.map((p) => p.firstName)).toEqual(['Kevin', 'Tanner', 'John', 'Jane', 'Peter']);

await expect.element(page.getByRole('row').nth(1)).toHaveTextContent('Kevin');
await expect.element(page.getByRole('row').nth(2)).toHaveTextContent('Tanner');
});

it('should show row action buttons on hover and respect disabled state', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,6 @@
width: 100%;
}

.reorderColumn {
width: vars.$reorder-column-width;
}

.headerCell {
@include typography.body-sm-md;
color: var(--font-main);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { SELECT_COLUMN_ID } from '../../utils/constants';
import { DsStack } from '../../../ds-stack';

const DsTableHeader = <TData,>({ table }: DsTableHeaderProps<TData>) => {
const { stickyHeader, bordered, reorderable, virtualized } = useDsTableContext<TData, unknown>();
const { stickyHeader, bordered, virtualized } = useDsTableContext<TData, unknown>();

return (
<TableHeader
Expand All @@ -26,9 +26,6 @@ const DsTableHeader = <TData,>({ table }: DsTableHeaderProps<TData>) => {
virtualized && styles.headerRowVirtualized,
)}
>
{reorderable && (
<TableHead className={classnames(styles.headerCell, styles.reorderColumn)}>Order</TableHead>
)}
{headerGroup.headers.map((header) => {
const headerStyle = getColumnSizeStyle(header.column.getSize(), virtualized);
const canSort = header.column.getCanSort();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,22 @@ import styles from './ds-table-row.module.scss';
import { useDsTableContext } from '../../context/ds-table-context';
import { mergeRefs } from '../../../../utils/merge-refs';
import { getColumnSizeStyle } from '../../utils/column-size';
import { EXPANDER_COLUMN_ID, SELECT_COLUMN_ID } from '../../utils/constants';
import { EXPANDER_COLUMN_ID, REORDER_COLUMN_ID, SELECT_COLUMN_ID } from '../../utils/constants';

interface DsRowDragHandleProps {
isDragging: boolean;
attributes: ReturnType<typeof useSortable>['attributes'];
listeners: ReturnType<typeof useSortable>['listeners'];
style?: React.CSSProperties;
}

const DsRowDragHandle = ({ isDragging, attributes, listeners }: DsRowDragHandleProps) => {
const DsRowDragHandle = ({ isDragging, attributes, listeners, style }: DsRowDragHandleProps) => {
return (
<TableCell
className={classnames(styles.tableCell, styles.cellReorder, {
[styles.isDragging]: isDragging,
})}
style={style}
>
<DsIcon
className={styles.rowDragHandle}
Expand Down Expand Up @@ -92,13 +94,23 @@ const DsTableRow = <TData,>({ ref, row, isSelected }: DsTableRowProps<TData>) =>
onClick={() => onRowClick?.(row.original)}
onDoubleClick={() => onRowDoubleClick?.(row.original)}
>
{reorderable && (
<DsRowDragHandle isDragging={isDragging} attributes={attributes} listeners={listeners} />
)}
{row.getVisibleCells().map((cell, idx) => {
const isLastColumn = idx === row.getVisibleCells().length - 1;
const cellStyle = getColumnSizeStyle(cell.column.getSize());

if (cell.column.id === REORDER_COLUMN_ID) {
return (
<DsRowDragHandle
key={cell.id}
isDragging={isDragging}
attributes={attributes}
listeners={listeners}
style={cellStyle}
/>
);
}

const isLastColumn = idx === row.getVisibleCells().length - 1;

return (
<TableCell
key={cell.id}
Expand Down Expand Up @@ -126,10 +138,7 @@ const DsTableRow = <TData,>({ ref, row, isSelected }: DsTableRowProps<TData>) =>

{isExpanded && renderExpandedRow && (
<TableRow className={styles.expandedRow}>
<TableCell
colSpan={row.getVisibleCells().length + (reorderable ? 1 : 0)}
className={styles.tableCell}
>
<TableCell colSpan={row.getVisibleCells().length} className={styles.tableCell}>
{renderExpandedRow(row.original)}
</TableCell>
</TableRow>
Expand Down
21 changes: 19 additions & 2 deletions packages/design-system/src/components/ds-table/ds-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import {
EMPTY_TABLE_STATE_TEXT,
EXPANDER_COLUMN_ID,
EXPANDER_COLUMN_WIDTH,
REORDER_COLUMN_ID,
REORDER_COLUMN_WIDTH,
SELECT_COLUMN_ID,
SELECT_COLUMN_WIDTH,
} from './utils/constants';
Expand Down Expand Up @@ -136,6 +138,7 @@ const DsTable = <TData extends { id: string }, TValue>({

const hasExpanderColumn = !!expandable;
const hasSelectColumn = !!selectable;
const hasReorderColumn = reorderable && !virtualized;

const columns = useMemo<ColumnDef<TData, TValue>[]>(() => {
const augmentedColumns: ColumnDef<TData, TValue>[] = [...columnsProp];
Expand Down Expand Up @@ -164,8 +167,22 @@ const DsTable = <TData extends { id: string }, TValue>({
augmentedColumns.unshift(expanderColumn);
}

if (hasReorderColumn) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for tests?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added some

// Cell is rendered inline by DsTableRow when it encounters REORDER_COLUMN_ID,
// since the drag handle needs row-level useSortable state.
const reorderColumn: ColumnDef<TData, TValue> = {
id: REORDER_COLUMN_ID,
size: REORDER_COLUMN_WIDTH,
enableSorting: false,
enableResizing: false,
header: 'Order',
cell: () => null,
};
augmentedColumns.unshift(reorderColumn);
}

return augmentedColumns;
}, [columnsProp, hasExpanderColumn, hasSelectColumn, showSelectAllCheckbox]);
}, [columnsProp, hasExpanderColumn, hasReorderColumn, hasSelectColumn, showSelectAllCheckbox]);

const table = useReactTable({
data: reorderable ? data : tableData,
Expand Down Expand Up @@ -237,7 +254,7 @@ const DsTable = <TData extends { id: string }, TValue>({

const renderEmptyState = () => (
<TableRow>
<TableCell colSpan={columns.length + (reorderable ? 1 : 0)} className={styles.emptyState}>
<TableCell colSpan={columns.length} className={styles.emptyState}>
{emptyState || EMPTY_TABLE_STATE_TEXT}
</TableCell>
</TableRow>
Expand Down
11 changes: 11 additions & 0 deletions packages/design-system/src/components/ds-table/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,14 @@ export const SELECT_COLUMN_ID = 'select';
* Width (in px) of the selection column.
*/
export const SELECT_COLUMN_WIDTH = 36;

/**
* Column id used for the synthetic reorder column injected when `reorderable` is set
* (non-virtualized tables only).
*/
export const REORDER_COLUMN_ID = 'reorder';

/**
* Width (in px) of the reorder column.
*/
export const REORDER_COLUMN_WIDTH = 60;
Loading