Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Table): add defaultSelectedIds prop #2354

Merged
merged 8 commits into from
Sep 9, 2024
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
6 changes: 6 additions & 0 deletions .changeset/poor-geese-hug.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@razorpay/blade": patch
---

feat(Table): add `defaultSelectedIds` prop

Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ describe('<BottomSheet />', () => {
);
expect(queryByTestId('bottomsheet-body')).not.toBeVisible();
mockConsoleError.mockRestore();
});
}, 10000);

it('should compose with Dropdown multi select', async () => {
const mockConsoleError = jest.spyOn(console, 'error').mockImplementation();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ describe('<BottomSheet /> & <Dropdown /> with <AutoComplete />', () => {

await waitFor(() => expect(queryByTestId('bottomsheet-body')).not.toBeVisible());
expect(selectInput.value).toBe('Mumbai');
});
}, 10000);

// Flaky test. Skipping for now. Should be replicated into E2E eventually
it.skip('should handle AutoComplete behaviour in multiselect', async () => {
Expand Down
14 changes: 13 additions & 1 deletion packages/blade/src/components/Table/Table.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { MetaConstants, metaAttribute } from '~utils/metaAttribute';
import { assignWithoutSideEffects } from '~utils/assignWithoutSideEffects';
import { useTheme } from '~components/BladeProvider';
import getIn from '~utils/lodashButBetter/get';
import { makeAccessible } from '~utils/makeAccessible';

const rowSelectType: Record<
NonNullable<TableProps<unknown>['selectionType']>,
Expand Down Expand Up @@ -137,10 +138,13 @@ const _Table = <Item,>({
isLoading = false,
isRefreshing = false,
showBorderedCells = false,
defaultSelectedIds = [],
...styledProps
}: TableProps<Item>): React.ReactElement => {
const { theme } = useTheme();
const [selectedRows, setSelectedRows] = React.useState<TableNode<unknown>['id'][]>([]);
const [selectedRows, setSelectedRows] = React.useState<TableNode<unknown>['id'][]>(
selectionType !== 'none' ? defaultSelectedIds : [],
);
const [disabledRows, setDisabledRows] = React.useState<TableNode<unknown>['id'][]>([]);
const [totalItems, setTotalItems] = React.useState(data.nodes.length || 0);
const [paginationType, setPaginationType] = React.useState<NonNullable<TablePaginationType>>(
Expand Down Expand Up @@ -265,6 +269,13 @@ const _Table = <Item,>({
data,
{
onChange: onSelectChange,
state: {
...(selectionType === 'multiple'
? { ids: selectedRows }
: selectionType === 'single'
? { id: selectedRows[0] }
: {}),
},
},
{
clickType:
Expand Down Expand Up @@ -489,6 +500,7 @@ const _Table = <Item,>({
height,
}}
pagination={hasPagination ? paginationConfig : null}
{...makeAccessible({ multiSelectable: selectionType === 'multiple' })}
{...metaAttribute({ name: MetaConstants.Table })}
>
{children}
Expand Down
2 changes: 2 additions & 0 deletions packages/blade/src/components/Table/TableBody.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { MetaConstants, metaAttribute } from '~utils/metaAttribute';
import { assignWithoutSideEffects } from '~utils/assignWithoutSideEffects';
import { getFocusRingStyles } from '~utils/getFocusRingStyles';
import { size } from '~tokens/global';
import { makeAccessible } from '~utils/makeAccessible';

const StyledBody = styled(Body)<{
$isSelectable: boolean;
Expand Down Expand Up @@ -326,6 +327,7 @@ const _TableRow = <Item,>({
className={isDisabled ? 'disabled-row' : ''}
onMouseEnter={() => onHover?.({ item })}
onClick={() => onClick?.({ item })}
{...makeAccessible({ selected: isSelected })}
{...metaAttribute({ name: MetaConstants.TableRow })}
>
{isMultiSelect && (
Expand Down
112 changes: 111 additions & 1 deletion packages/blade/src/components/Table/__tests__/Table.web.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -790,7 +790,7 @@ describe('<Table />', () => {
it('should render table with multi select', async () => {
const onSelectionChange = jest.fn();
const user = userEvent.setup();
const { getByText, getAllByRole } = renderWithTheme(
const { getByText, getAllByRole, getByRole } = renderWithTheme(
<Table
data={{ nodes: nodes.slice(0, 5) }}
selectionType="multiple"
Expand Down Expand Up @@ -828,6 +828,7 @@ describe('<Table />', () => {
</Table>,
);

expect(getByRole('table')).toHaveAttribute('aria-multiselectable', 'true');
expect(getByText('Showing 1-5 Items')).toBeInTheDocument();
expect(getAllByRole('checkbox')).toHaveLength(6);
const firstSelectableRow = getByText('rzp01').closest('td');
Expand All @@ -845,6 +846,115 @@ describe('<Table />', () => {
expect(onSelectionChange).toHaveBeenCalledWith({ values: [], selectedIds: [] });
});

it('should render table with single select and defaultSelectedIds', async () => {
const onSelectionChange = jest.fn();
const user = userEvent.setup();
const { getByText } = renderWithTheme(
<Table
data={{ nodes: nodes.slice(0, 5) }}
selectionType="single"
onSelectionChange={onSelectionChange}
defaultSelectedIds={['1']}
>
{(tableData) => (
<>
<TableHeader>
<TableHeaderRow>
<TableHeaderCell>Payment ID</TableHeaderCell>
<TableHeaderCell>Amount</TableHeaderCell>
<TableHeaderCell>Status</TableHeaderCell>
<TableHeaderCell>Type</TableHeaderCell>
<TableHeaderCell>Method</TableHeaderCell>
<TableHeaderCell>Name</TableHeaderCell>
</TableHeaderRow>
</TableHeader>
<TableBody>
{tableData.map((tableItem, index) => (
<TableRow item={tableItem} key={index}>
<TableCell>{tableItem.paymentId}</TableCell>
<TableCell>{tableItem.amount}</TableCell>
<TableCell>{tableItem.status}</TableCell>
<TableCell>{tableItem.type}</TableCell>
<TableCell>{tableItem.method}</TableCell>
<TableCell>{tableItem.name}</TableCell>
</TableRow>
))}
</TableBody>
</>
)}
</Table>,
);
const firstSelectableRow = getByText('rzp01').closest('tr');
expect(firstSelectableRow).toHaveAttribute('aria-selected', 'true');
const secondSelectableRow = getByText('rzp02').closest('td');
if (secondSelectableRow) await user.click(secondSelectableRow);
expect(onSelectionChange).toHaveBeenCalledWith({
values: [nodes[1]],
selectedIds: ['2'],
});
});

it('should render table with multi select and defaultSelectedIds', async () => {
const onSelectionChange = jest.fn();
const user = userEvent.setup();
const { getByText, getAllByRole } = renderWithTheme(
<Table
data={{ nodes: nodes.slice(0, 5) }}
selectionType="multiple"
onSelectionChange={onSelectionChange}
defaultSelectedIds={['1', '2']}
toolbar={<TableToolbar />}
>
{(tableData) => (
<>
<TableHeader>
<TableHeaderRow>
<TableHeaderCell>Payment ID</TableHeaderCell>
<TableHeaderCell>Amount</TableHeaderCell>
<TableHeaderCell>Status</TableHeaderCell>
<TableHeaderCell>Type</TableHeaderCell>
<TableHeaderCell>Method</TableHeaderCell>
<TableHeaderCell>Name</TableHeaderCell>
</TableHeaderRow>
</TableHeader>
<TableBody>
{tableData.map((tableItem, index) => (
<TableRow item={tableItem} key={index}>
<TableCell>{tableItem.paymentId}</TableCell>
<TableCell>
<Amount value={tableItem.amount} />
</TableCell>
<TableCell>{tableItem.status}</TableCell>
<TableCell>{tableItem.type}</TableCell>
<TableCell>{tableItem.method}</TableCell>
<TableCell>{tableItem.name}</TableCell>
</TableRow>
))}
</TableBody>
</>
)}
</Table>,
);

expect(getByText('2 Items Selected')).toBeInTheDocument();
expect(getAllByRole('checkbox')).toHaveLength(6);
const firstSelectableRow = getByText('rzp01').closest('tr');
expect(firstSelectableRow).toHaveAttribute('aria-selected', 'true');
const secondSelectableRow = getByText('rzp02').closest('tr');
expect(secondSelectableRow).toHaveAttribute('aria-selected', 'true');
const thirdSelectableRow = getByText('rzp03').closest('td');
if (thirdSelectableRow) await user.click(thirdSelectableRow);
expect(onSelectionChange).toHaveBeenCalledWith({
values: [nodes[0], nodes[1], nodes[2]],
selectedIds: ['1', '2', '3'],
});

expect(getByText('3 Items Selected')).toBeInTheDocument();
const deselectButton = getByText('Deselect');
await user.click(deselectButton);
expect(onSelectionChange).toHaveBeenCalledWith({ values: [], selectedIds: [] });
});

it('should render table with client side pagination', async () => {
const onPageChange = jest.fn();
const onPageSizeChange = jest.fn();
Expand Down
Loading
Loading