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

Add checkbox functionality to tables #5872

Merged
merged 11 commits into from
Jun 2, 2023
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
8 changes: 8 additions & 0 deletions app/react/App/styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -1150,6 +1150,14 @@ input:checked + .toggle-bg {
margin: 0px;
}

.m-1 {
margin: 0.25rem;
}

.m-4 {
margin: 1rem;
}

.m-auto {
margin: auto;
}
Expand Down
22 changes: 22 additions & 0 deletions app/react/V2/Components/UI/IndeterminateCheckbox.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import React, { HTMLProps, useEffect, useRef } from 'react';

const IndeterminateCheckbox = ({
indeterminate,
className = '',
...rest
}: { indeterminate?: boolean } & HTMLProps<HTMLInputElement>) => {
const ref = useRef<HTMLInputElement>(null!);

useEffect(() => {
if (typeof indeterminate === 'boolean') {
ref.current.indeterminate = !rest.checked && indeterminate;
}
}, [ref, indeterminate, rest.checked]);

return (
// eslint-disable-next-line react/jsx-props-no-spreading
<input type="checkbox" ref={ref} className={`rounded cursor-pointer ${className}`} {...rest} />
);
};

export { IndeterminateCheckbox };
93 changes: 54 additions & 39 deletions app/react/V2/Components/UI/Table.tsx
Original file line number Diff line number Diff line change
@@ -1,64 +1,82 @@
import React, { useMemo, useState } from 'react';
/* eslint-disable react/jsx-props-no-spreading */
/* eslint-disable react/no-multi-comp */
import React, { useEffect, useMemo, useState } from 'react';
import {
flexRender,
getSortedRowModel,
getCoreRowModel,
useReactTable,
SortingState,
TableState,
ColumnDef,
CellContext,
Column,
} from '@tanstack/react-table';
import { ChevronUpDownIcon, ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/20/solid';

type ColumnWithClassName<T> = ColumnDef<T, any> & {
className?: string;
};

type CellContextWithMeta<T, U> = CellContext<T, U> & {
column: Column<T> & { columnDef: ColumnWithClassName<T> };
};

interface TableProps<T> {
columns: ColumnWithClassName<T>[];
data: T[];
title?: string | React.ReactNode;
initialState?: Partial<TableState>;
}

const getIcon = (sorting: false | 'asc' | 'desc') => {
switch (sorting) {
case false:
return <ChevronUpDownIcon className="w-4" />;
case 'asc':
return <ChevronUpIcon className="w-4" />;
case 'desc':
default:
return <ChevronDownIcon className="w-4" />;
}
};
import {
TableProps,
CheckBoxHeader,
CheckBoxCell,
getIcon,
ColumnWithClassName,
} from './TableTypes';

const applyForSelection = (
withSelection: any,
withOutSelection: any,
enableSelection: boolean = false
) => (enableSelection ? withSelection : withOutSelection);
// eslint-disable-next-line comma-spacing
const Table = <T,>({ columns, data, title, initialState }: TableProps<T>) => {
const Table = <T,>({
columns,
data,
title,
initialState,
enableSelection,
onSelection,
}: TableProps<T>) => {
const [sorting, setSorting] = useState<SortingState>(initialState?.sorting || []);
const [rowSelection, setRowSelection] = useState({});

const memoizedColumns = useMemo(
() => [
...applyForSelection(
[
{
id: 'select',
header: CheckBoxHeader,
cell: CheckBoxCell,
},
],
[],
enableSelection
),
...columns,
],
[columns, enableSelection]
);

const memoizedColumns = useMemo(() => columns, [columns]);
const memoizedData = useMemo<T[]>(() => data, [data]);

const table = useReactTable({
columns: memoizedColumns,
data: memoizedData,
state: {
sorting,
...applyForSelection({ rowSelection }, {}, enableSelection),
},
enableRowSelection: enableSelection,
onRowSelectionChange: applyForSelection(setRowSelection, () => undefined, enableSelection),
onSortingChange: setSorting,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
});

useEffect(() => {
const selectedRows = table.getSelectedRowModel().flatRows;

if (onSelection) {
onSelection(selectedRows);
}
}, [onSelection, rowSelection, table]);

return (
<div className="overflow-x-auto relative">
<div className="relative overflow-x-auto">
<table className="w-full text-sm text-left">
{title && (
<caption className="p-5 text-lg font-semibold text-left text-gray-900 bg-white">
Expand Down Expand Up @@ -108,7 +126,4 @@ const Table = <T,>({ columns, data, title, initialState }: TableProps<T>) => {
</div>
);
};

export type { CellContextWithMeta, ColumnWithClassName };

export { Table };
68 changes: 68 additions & 0 deletions app/react/V2/Components/UI/TableTypes.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/* eslint-disable react/jsx-props-no-spreading */
/* eslint-disable react/no-multi-comp */
import React, { Dispatch, SetStateAction } from 'react';
import {
ColumnDef,
CellContext,
Column,
TableState,
Row,
Table as TableDef,
} from '@tanstack/react-table';
import { ChevronUpDownIcon, ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/20/solid';
import { IndeterminateCheckbox } from './IndeterminateCheckbox';

type ColumnWithClassName<T> = ColumnDef<T, any> & {
className?: string;
};

type CellContextWithMeta<T, U> = CellContext<T, U> & {
column: Column<T> & { columnDef: ColumnWithClassName<T> };
};

interface TableProps<T> {
columns: ColumnWithClassName<T>[];
data: T[];
title?: string | React.ReactNode;
initialState?: Partial<TableState>;
enableSelection?: boolean;
onSelection?: Dispatch<SetStateAction<Row<T>[]>>;
}

const getIcon = (sorting: false | 'asc' | 'desc') => {
switch (sorting) {
case false:
return <ChevronUpDownIcon className="w-4" />;
case 'asc':
return <ChevronUpIcon className="w-4" />;
case 'desc':
default:
return <ChevronDownIcon className="w-4" />;
}
};

// eslint-disable-next-line comma-spacing
const CheckBoxHeader = <T,>({ table }: { table: TableDef<T> }) => (
<IndeterminateCheckbox
{...{
checked: table.getIsAllRowsSelected(),
indeterminate: table.getIsSomeRowsSelected(),
onChange: table.getToggleAllRowsSelectedHandler(),
}}
/>
);

// eslint-disable-next-line comma-spacing
const CheckBoxCell = <T,>({ row }: { row: Row<T> }) => (
<IndeterminateCheckbox
{...{
checked: row.getIsSelected(),
disabled: !row.getCanSelect(),
indeterminate: row.getIsSomeSelected(),
onChange: row.getToggleSelectedHandler(),
}}
/>
);

export type { TableProps, ColumnWithClassName, CellContextWithMeta };
export { CheckBoxHeader, CheckBoxCell, getIcon };
1 change: 1 addition & 0 deletions app/react/V2/Components/UI/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export type { TableProps } from './TableTypes';
export { Button } from './Button';
export { Modal } from './Modal';
export { Pill } from './Pill';
Expand Down
21 changes: 20 additions & 1 deletion app/react/V2/Components/UI/specs/Table.cy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { map } from 'lodash';
import { composeStories } from '@storybook/react';
import * as stories from 'app/stories/Table.stories';

const { Basic, WithActions } = composeStories(stories);
const { Basic, WithActions, WithCheckboxes } = composeStories(stories);

describe('Table', () => {
const data = Basic.args.data || [];
Expand Down Expand Up @@ -56,4 +56,23 @@ describe('Table', () => {
checkRowContent(1, ['Entity 2', '2', data[0].description]);
});
});

describe('Selections', () => {
it('should select items from each table', () => {
mount(<WithCheckboxes />);
cy.get('table').eq(0).get('thead > tr > th').eq(0).click();

cy.get('tbody')
.eq(1)
.within(() => {
cy.get('input[type="checkbox"]').eq(0).check();
cy.get('input[type="checkbox"]').eq(2).check();
});

cy.contains('p', 'Selected items for Table A: 3');
cy.contains('p', 'Selections of Table A: Entity 2, Entity 1, Entity 3,');
cy.contains('p', 'Selected items for Table B: 2');
cy.contains('p', 'Selections of Table B: Entity 2, Entity 3,');
});
});
});
4 changes: 1 addition & 3 deletions app/react/V2/Routes/Settings/Languages/LanguagesList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ import { Row, createColumnHelper } from '@tanstack/react-table';
import { Translate, I18NApi } from 'app/I18N';
import { RequestParams } from 'app/utils/RequestParams';
import { settingsAtom } from 'app/V2/atoms/settingsAtom';
import { ConfirmationModal } from 'app/V2/Components/UI/ConfirmationModal';
import { Button } from 'V2/Components/UI/Button';
import { Table } from 'V2/Components/UI/Table';
import { Button, Table, ConfirmationModal } from 'V2/Components/UI';
import { useApiCaller } from 'V2/CustomHooks/useApiCaller';
import { SettingsContent } from 'app/V2/Components/Layouts/SettingsContent';
import { LanguageSchema } from 'shared/types/commonTypes';
Expand Down
Loading
Loading