Skip to content

Commit

Permalink
feat: search in table colum settings
Browse files Browse the repository at this point in the history
  • Loading branch information
polikashina committed Jun 4, 2024
1 parent 95289c1 commit 3abccea
Show file tree
Hide file tree
Showing 7 changed files with 174 additions and 19 deletions.
24 changes: 14 additions & 10 deletions src/components/Table/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,10 +237,11 @@ const MyTable1 = withTableSettings({sortable: false})(Table);

### Options

| Name | Description | Type | Default |
| :------- | :------------------------------------------------ | :------------: | :-----: |
| width | Settings' popup width | `number` `fit` | |
| sortable | Whether or not add ability to sort settings items | `boolean` | `true` |
| Name | Description | Type | Default |
| :--------- | :-------------------------------------------------- | :------------: | :-----: |
| width | Settings' popup width | `number` `fit` | |
| sortable | Whether or not add ability to sort settings items | `boolean` | `true` |
| filterable | Whether or not add ability to filter settings items | `boolean` | `false` |

### ColumnMeta

Expand All @@ -251,12 +252,15 @@ const MyTable1 = withTableSettings({sortable: false})(Table);

### Properties

| Name | Description | Type |
| :----------------- | :------------------------------ | :------------------------------------------: |
| settingsPopupWidth | TableColumnSetup pop-up width | `number` `fit` |
| settings | Current settings | `TableSettingsData` |
| updateSettings | Settings update handle | `(data: TableSettingsData) => Promise<void>` |
| renderControls | Allows to render custom actions | `RenderControls` |
| Name | Description | Type |
| :--------------------- | :----------------------------------------------------------- | :------------------------------------------------------: |
| settingsPopupWidth | TableColumnSetup pop-up width | `number` `fit` |
| settings | Current settings | `TableSettingsData` |
| updateSettings | Settings update handle | `(data: TableSettingsData) => Promise<void>` |
| renderControls | Allows to render custom actions | `RenderControls` |
| filterPlaceholder | Text that appears in the control when no search value is set | `string` |
| filterEmptyPlaceholder | Text that appears when no one item is found | `string` |
| filterItems | Function for filtering items | `(item: TableColumnSetupItem, value: string) => boolean` |

### TableSettingsData

Expand Down
19 changes: 19 additions & 0 deletions src/components/Table/__stories__/Table.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {WithTableSettingsCustomActionsShowcase} from './WithTableSettingsCustomA
import {
TableWithAction,
TableWithCopy,
TableWithFilterableSettings,
TableWithSelection,
TableWithSettings,
TableWithSettingsFactory,
Expand Down Expand Up @@ -233,6 +234,24 @@ HOCWithTableSettings.args = {
columns: columnsWithSettings,
};

const WithFilterableSettingsTemplate: StoryFn<TableProps<DataItem>> = (args) => {
const [settings, setSettings] = React.useState<TableSettingsData>(DEFAULT_SETTINGS);
return (
<TableWithFilterableSettings
{...args}
settings={settings}
updateSettings={setSettings}
filterPlaceholder="Filter list"
filterEmptyPlaceholder="No results"
/>
);
};

export const HOCWithFilterableTableSettings = WithFilterableSettingsTemplate.bind({});
HOCWithFilterableTableSettings.parameters = {
disableStrictMode: true,
};

export const HOCWithTableSettingsFactory = WithTableSettingsTemplate.bind({});
HOCWithTableSettingsFactory.parameters = {
isFactory: true,
Expand Down
4 changes: 4 additions & 0 deletions src/components/Table/__stories__/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,5 +97,9 @@ export const TableWithAction = withTableActions<DataItem>(Table);
export const TableWithCopy = withTableCopy<DataItem>(Table);
export const TableWithSelection = withTableSelection<DataItem>(Table);
export const TableWithSettings = withTableSettings<DataItem>(Table);
export const TableWithFilterableSettings = withTableSettings<DataItem>({
filterable: true,
width: 200,
})(Table);
export const TableWithSettingsFactory = withTableSettings<DataItem>({sortable: false})(Table);
export const TableWithSorting = withTableSorting<DataItem>(Table);
46 changes: 45 additions & 1 deletion src/components/Table/__tests__/Table.withTableSettings.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react';

import userEvent from '@testing-library/user-event';

import {render, screen} from '../../../../test-utils/utils';
import {fireEvent, render, screen} from '../../../../test-utils/utils';
import {Button} from '../../Button';
import {Table} from '../Table';
import type {TableColumnConfig, TableProps} from '../Table';
Expand Down Expand Up @@ -331,4 +331,48 @@ describe('withTableSettings', () => {
expect(customControl).toBeVisible();
});
});

describe('filterableSettings', () => {
const TableWithSettings = withTableSettings<SomeItem>({sortable: true, filterable: true})(
Table,
);
const settings = columns.map<TableSetting>((column) => ({id: column.id, isSelected: true}));
const updateSettings = jest.fn();
const placeholder = 'Filter list';

it('should filter columns', async () => {
render(
<TableWithSettings
columns={columns}
data={data}
settings={settings}
filterPlaceholder={placeholder}
updateSettings={updateSettings}
/>,
);

await userEvent.click(screen.getByRole('button', {name: 'Table settings'}));
const textInput = screen.getByRole('textbox') as HTMLInputElement;
expect(textInput).toBeVisible();
expect(textInput.placeholder).toBe(placeholder);

const column = screen.getByRole('button', {name: 'description'});
expect(column.hasAttribute('draggable')).toBeTruthy();

fireEvent.change(textInput, {target: {value: 'na'}});
const filteredOption = screen.getByRole('option', {name: 'name'});
expect(filteredOption).toBeInTheDocument();
expect(filteredOption.hasAttribute('draggable')).toBeFalsy();
expect(screen.getAllByRole('option')).toHaveLength(1);

fireEvent.change(textInput, {target: {value: ''}});
expect(screen.getByRole('button', {name: 'id'}).hasAttribute('draggable')).toBeTruthy();
expect(
screen.getByRole('button', {name: 'name'}).hasAttribute('draggable'),
).toBeTruthy();
expect(
screen.getByRole('button', {name: 'description'}).hasAttribute('draggable'),
).toBeTruthy();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,15 @@ $block: '.#{variables.$ns}inner-table-column-setup';
&__controls {
margin: var(--g-spacing-1) var(--g-spacing-1) 0;
}

&__filter-input {
box-sizing: border-box;
padding: 0 var(--g-spacing-2) var(--g-spacing-1);

border-block-end: 1px solid var(--g-color-line-generic);
}

&__empty-placeholder {
padding: var(--g-spacing-2);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ import type {PopperPlacement} from '../../../../../hooks/private';
import {createOnKeyDownHandler} from '../../../../../hooks/useActionHandlers/useActionHandlers';
import {Button} from '../../../../Button';
import {Icon} from '../../../../Icon';
import {Text} from '../../../../Text';
import {TreeSelect} from '../../../../TreeSelect/TreeSelect';
import type {
TreeSelectProps,
TreeSelectRenderContainer,
TreeSelectRenderItem,
} from '../../../../TreeSelect/types';
import {TextInput} from '../../../../controls/TextInput';
import {Flex} from '../../../../layout/Flex/Flex';
import type {ListItemCommonProps, ListItemViewProps} from '../../../../useList';
import {ListContainerView, ListItemView} from '../../../../useList';
Expand All @@ -33,6 +35,8 @@ import './TableColumnSetup.scss';

const b = block('inner-table-column-setup');
const controlsCn = b('controls');
const filterInputCn = b('filter-input');
const emptyPlaceholderCn = b('empty-placeholder');

const reorderArray = <T extends unknown>(list: T[], startIndex: number, endIndex: number): T[] => {
const result = [...list];
Expand Down Expand Up @@ -242,6 +246,17 @@ const mapItemDataToProps = (item: TableColumnSetupItem): ListItemCommonProps =>
};
};

const defaultFilterItemsFn = (item: TableColumnSetupItem, value: string) => {
return typeof item.title === 'string'
? item.title.toLowerCase().includes(value.toLowerCase())
: true;
};

const useEmptyRenderContainer = (placeholder?: string): TreeSelectRenderContainer<{}> => {
const emptyRenderContainer = () => <Text className={emptyPlaceholderCn}>{placeholder}</Text>;
return emptyRenderContainer;
};

export type RenderControls = (params: {
DefaultApplyButton: React.ComponentType;
/**
Expand Down Expand Up @@ -269,6 +284,11 @@ export interface TableColumnSetupProps {

defaultItems?: TableColumnSetupItem[];
showResetButton?: boolean | ((currentItems: TableColumnSetupItem[]) => boolean);

filterable?: boolean;
filterPlaceholder?: string;
filterEmptyPlaceholder?: string;
filterItems?: (item: TableColumnSetupItem, value: string) => boolean;
}

export const TableColumnSetup = (props: TableColumnSetupProps) => {
Expand All @@ -283,9 +303,22 @@ export const TableColumnSetup = (props: TableColumnSetupProps) => {
className,
defaultItems = propsItems,
showResetButton: propsShowResetButton,
filterable,
filterPlaceholder,
filterEmptyPlaceholder,
filterItems = defaultFilterItemsFn,
} = props;

const [open, setOpen] = React.useState(false);
const [filter, setFilter] = React.useState('');
const [filteredItems, setFilteredItems] = React.useState<TableColumnSetupItem[]>([]);

const [sortingEnabled, setSortingEnabled] = React.useState(sortable);
const [prevSortingEnabled, setPrevSortingEnabled] = React.useState(sortable);
if (sortable !== prevSortingEnabled) {
setPrevSortingEnabled(sortable);
setSortingEnabled(sortable);
}

const [items, setItems] = React.useState(propsItems);
const [prevPropsItems, setPrevPropsItems] = React.useState(propsItems);
Expand All @@ -298,7 +331,7 @@ export const TableColumnSetup = (props: TableColumnSetupProps) => {
const onApply = () => {
const newSettings = items.map<TableSetting>(({id, isSelected}) => ({id, isSelected}));
propsOnUpdate(newSettings);
setOpen(false);
onOpenChange(false);
};

const DefaultApplyButton = () => (
Expand Down Expand Up @@ -342,7 +375,7 @@ export const TableColumnSetup = (props: TableColumnSetupProps) => {
),
});

const dndRenderItem = useDndRenderItem(sortable);
const dndRenderItem = useDndRenderItem(sortingEnabled);

const renderControl: TreeSelectProps<unknown>['renderControl'] = ({toggleOpen}) => {
const onKeyDown = createOnKeyDownHandler(toggleOpen);
Expand All @@ -359,9 +392,11 @@ export const TableColumnSetup = (props: TableColumnSetupProps) => {

const onOpenChange = (open: boolean) => {
setOpen(open);

if (open === false) {
setItems(propsItems);
setFilter('');
setFilteredItems([]);
setSortingEnabled(sortable);
}
};

Expand All @@ -376,6 +411,29 @@ export const TableColumnSetup = (props: TableColumnSetupProps) => {

const value = React.useMemo(() => prepareValue(items), [items]);

const emptyRenderContainer = useEmptyRenderContainer(filterEmptyPlaceholder);

const onFilterValueUpdate = (value: string) => {
setFilter(value);
setFilteredItems(items.filter((item) => filterItems(item, value)));
setSortingEnabled(!value.length);
};

const slotBeforeListBody = filterable ? (
<TextInput
size="m"
view="clear"
placeholder={filterPlaceholder}
value={filter}
className={filterInputCn}
onUpdate={onFilterValueUpdate}
hasClear
/>
) : null;

const renderContainer =
filter && !filteredItems.length ? emptyRenderContainer : dndRenderContainer;

return (
<TreeSelect
className={b(null, className)}
Expand All @@ -384,12 +442,13 @@ export const TableColumnSetup = (props: TableColumnSetupProps) => {
size="l"
open={open}
value={value}
items={items}
items={filter ? filteredItems : items}
onUpdate={onUpdate}
popupWidth={popupWidth}
onOpenChange={onOpenChange}
placement={popupPlacement}
renderContainer={dndRenderContainer}
slotBeforeListBody={slotBeforeListBody}
renderContainer={renderContainer}
renderControl={renderControl}
renderItem={dndRenderItem}
/>
Expand Down
20 changes: 17 additions & 3 deletions src/components/Table/hoc/withTableSettings/withTableSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ export function getActualItems<I>(
export interface WithTableSettingsOptions {
width?: TreeSelectProps<any>['popupWidth'];
sortable?: boolean;
filterable?: boolean;
}

interface WithTableSettingsBaseProps {
Expand Down Expand Up @@ -143,8 +144,15 @@ interface WithoutDefaultSettings {
showResetButton?: boolean;
}

interface WithFilter {
filterPlaceholder?: string;
filterEmptyPlaceholder?: string;
filterItems?: (item: TableColumnSetupItem, value: string) => boolean;
}

export type WithTableSettingsProps = WithTableSettingsBaseProps &
(WithDefaultSettings | WithoutDefaultSettings);
(WithDefaultSettings | WithoutDefaultSettings) &
WithFilter;

const b = block('table');

Expand All @@ -167,7 +175,7 @@ export function withTableSettings<I extends TableDataItem, E extends {} = {}>(
) => React.ComponentType<TableProps<I> & WithTableSettingsProps & E>) {
function tableWithSettingsFactory(
TableComponent: React.ComponentType<TableProps<I> & E>,
{width, sortable}: WithTableSettingsOptions = {},
{width, sortable, filterable}: WithTableSettingsOptions = {},
) {
const componentName = getComponentName(TableComponent);

Expand All @@ -179,6 +187,9 @@ export function withTableSettings<I extends TableDataItem, E extends {} = {}>(
renderControls,
defaultSettings,
showResetButton,
filterPlaceholder,
filterEmptyPlaceholder,
filterItems,
...restTableProps
}: TableProps<I> & WithTableSettingsProps & E) {
const defaultActualItems = React.useMemo(() => {
Expand All @@ -191,14 +202,17 @@ export function withTableSettings<I extends TableDataItem, E extends {} = {}>(

const enhancedColumns = React.useMemo(() => {
const actualItems = getActualItems(columns, settings || []);

return enhanceSystemColumn(filterColumns(columns, actualItems), (systemColumn) => {
systemColumn.name = () => (
<div className={b('settings')}>
<TableColumnSetup
popupWidth={settingsPopupWidth || width}
popupPlacement={POPUP_PLACEMENT}
sortable={sortable}
filterable={filterable}
filterPlaceholder={filterPlaceholder}
filterEmptyPlaceholder={filterEmptyPlaceholder}
filterItems={filterItems}
onUpdate={updateSettings}
items={actualItems}
renderSwitcher={({onClick}) => (
Expand Down

0 comments on commit 3abccea

Please sign in to comment.