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(manager-react-components): add filters in datagrid #14203

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
@@ -1,42 +1,30 @@
import React, { useState } from 'react';
import { ColumnSort } from '@tanstack/react-table';
import { withRouter } from 'storybook-addon-react-router-v6';
import { applyFilters } from '@ovh-ux/manager-core-api';
import { useSearchParams } from 'react-router-dom';
import { Datagrid } from './datagrid.component';
import { DataGridTextCell } from './text-cell.component';
import { useColumnFilters } from '../filters';
import { columsTmp, columsFilters } from './datagrid.stories';

interface Item {
label: string;
price: number;
}

const columns = [
{
id: 'label',
cell: (item: Item) => {
return <DataGridTextCell>{item.label}</DataGridTextCell>;
},
label: 'Label',
},
{
id: 'price',
cell: (item: Item) => {
return <DataGridTextCell>{item.price} €</DataGridTextCell>;
},
label: 'Price',
},
];

const DatagridStory = ({
items,
isSortable,
columns = columsTmp,
}: {
items: Item[];
isSortable: boolean;
columns?: any;
}) => {
const [sorting, setSorting] = useState<ColumnSort>();
const [data, setData] = useState(items);
const [searchParams] = useSearchParams();
const { filters, addFilter, removeFilter } = useColumnFilters();

const fetchNextPage = () => {
const itemsIndex = data.length;
Expand All @@ -57,10 +45,11 @@ const DatagridStory = ({
)}
<Datagrid
columns={columns}
items={data}
items={applyFilters(data, filters)}
totalItems={data.length}
hasNextPage={data.length > 0 && data.length < 30}
onFetchNextPage={fetchNextPage}
filters={{ filters, add: addFilter, remove: removeFilter }}
{...(isSortable
? {
sorting,
Expand Down Expand Up @@ -99,6 +88,17 @@ export const Sortable = {
},
};

export const Filters = {
args: {
items: [...Array(10).keys()].map((_, i) => ({
label: `Item #${i}`,
price: Math.floor(1 + Math.random() * 100),
})),
isSortable: true,
columns: columsFilters,
},
};

export default {
title: 'Components/Datagrid Cursor',
component: DatagridStory,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
ColumnDef,
ColumnSort as TanstackColumnSort,
Expand All @@ -8,16 +9,28 @@
useReactTable,
getSortedRowModel,
} from '@tanstack/react-table';
import { ODS_ICON_NAME, ODS_BUTTON_VARIANT } from '@ovhcloud/ods-components';
import {
ODS_ICON_NAME,
ODS_BUTTON_VARIANT,
ODS_BUTTON_SIZE,
} from '@ovhcloud/ods-components';
import {
OdsPopover,
OdsButton,
OdsIcon,
OdsPagination,
OdsTable,
} from '@ovhcloud/ods-components/react';
import { useTranslation } from 'react-i18next';
import {
FilterComparator,
FilterCategories,
FilterTypeCategories,
} from '@ovh-ux/manager-core-api';
import { FilterAdd, FilterList } from '../filters';
import { FilterWithLabel } from '../filters/interface';
import { DataGridTextCell } from './text-cell.component';
import './translations';
import { type } from 'os';

Check failure on line 33 in packages/manager-react-components/src/components/datagrid/datagrid.component.tsx

View workflow job for this annotation

GitHub Actions / Lint Code Base

`os` import should occur before import of `../filters`

Check failure on line 33 in packages/manager-react-components/src/components/datagrid/datagrid.component.tsx

View workflow job for this annotation

GitHub Actions / Lint Code Base

`os` import should occur before import of `../filters`

export type ColumnSort = TanstackColumnSort;
export type PaginationState = TanstackPaginationState;
Expand All @@ -35,6 +48,23 @@
label: string;
/** is the column sortable ? (defaults is true) */
isSortable?: boolean;
/** set column comparator for the filter */
comparator?: FilterComparator;
/* Filters displayed for the column */
type?: FilterTypeCategories;
}

type ColumnFilterProps = {
key: string;
value: string | string[];
comparator: FilterComparator;
label: string;
};

export interface FilterProps {
filters: FilterWithLabel[];
add: (filters: ColumnFilterProps) => void;
remove: (filter: FilterWithLabel) => void;
}

export interface DatagridProps<T> {
Expand Down Expand Up @@ -68,11 +98,17 @@
/** setSorting?: OnChangeFn<SortingState>; */
/** label displayed if there is no item in the datagrid */
noResultLabel?: string;
/** List of filters and handlers to add, remove */
filters?: FilterProps;
/** Enables columns filters */
isFilterable?: boolean;
}

export const Datagrid = <T,>({
columns,
items,
filters,
isFilterable = true,
totalItems,
pagination,
sorting,
Expand Down Expand Up @@ -131,8 +167,60 @@
}),
});

const [columnsFilters, setColumnsFilters] = useState([]);
useEffect(() => {
const clmFilters = columns
.filter((item) => 'comparator' in item || 'type' in item)
.map((column) => ({
id: column.id,
label: column.label,
...(column?.type && { comparators: FilterCategories[column.type] }),
...(column?.comparator && { comparators: column.comparator }),
}));
setColumnsFilters(clmFilters);
}, [columns]);

return (
<div>
{isFilterable && (
<>
{columnsFilters.length > 0 && (
<div className="flex flex-row-reverse pb-[5px]">
<div id="datagrid-filter-popover-trigger">
<OdsButton
slot="datagrid-filter-popover-trigger"
size={ODS_BUTTON_SIZE.sm}
variant={ODS_BUTTON_VARIANT.ghost}
icon={ODS_ICON_NAME.filter}
label=""
/>
</div>
<OdsPopover
triggerId="datagrid-filter-popover-trigger"
with-arrow
>
<FilterAdd
columns={columnsFilters}
onAddFilter={(addedFilter, column) => {
filters.add({
...addedFilter,
label: column.label,
});
}}
/>
</OdsPopover>
</div>
)}
{filters?.filters.length > 0 && (
<div id="datagrid-filter-list" className="my-5">
<FilterList
filters={filters.filters}
onRemoveFilter={filters.remove}
/>
</div>
)}
</>
)}
<div className={`contents px-[1px] ${className || ''}`}>
<OdsTable className="overflow-x-visible">
<table className="w-full border-collapse">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { vitest } from 'vitest';
import React, { useState } from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { FilterCategories } from '@ovh-ux/manager-core-api';
import {
ColumnSort,
Datagrid,
DatagridColumn,
PaginationState,
FilterProps,
} from './datagrid.component';
import DataGridTextCell from './text-cell.component';

Expand All @@ -32,11 +33,13 @@ const sampleColumns = [
return <span>{name}</span>;
},
label: 'Name',
comparator: FilterCategories.String,
},
{
id: 'another-column',
label: 'test',
cell: () => <DataGridTextCell />,
comparator: FilterCategories.String,
},
];

Expand All @@ -46,12 +49,14 @@ const DatagridTest = ({
pageIndex,
className,
noResultLabel,
filters,
}: {
columns: DatagridColumn<string>[];
columns: any;
items: string[];
pageIndex: number;
className?: string;
noResultLabel?: string;
filters?: FilterProps;
}) => {
const [pagination, setPagination] = useState<PaginationState>({
pageIndex,
Expand All @@ -70,6 +75,7 @@ const DatagridTest = ({
onSortChange={() => {}}
className={className || ''}
noResultLabel={noResultLabel}
filters={filters}
/>
);
};
Expand Down Expand Up @@ -220,3 +226,44 @@ it('should disable overflow of table', async () => {
);
expect(container.querySelectorAll('.overflow-hidden').length).toBe(1);
});

it('should disable overflow of table', async () => {
const { container } = render(
<DatagridTest
columns={sampleColumns}
items={[]}
pageIndex={0}
className={'overflow-hidden'}
/>,
);
expect(container.querySelectorAll('.overflow-hidden').length).toBe(1);
});

it('should display filter add and filter list', async () => {
const filters = {
filters: [
{
key: 'customName',
comparator: 'includes',
value: 'coucou',
label: 'customName',
},
],
add: null,
remove: null,
} as FilterProps;
console.info('sampleColumns : ', sampleColumns);
const { container } = render(
<DatagridTest
columns={sampleColumns}
items={[]}
pageIndex={0}
className={'overflow-hidden'}
filters={filters}
/>,
);
expect(
container.querySelectorAll('#datagrid-filter-popover-trigger').length,
).toBe(1);
expect(container.querySelectorAll('#datagrid-filter-list').length).toBe(1);
});
Loading
Loading