Skip to content

[WIP]feat: combine search props #1152

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

Open
wants to merge 10 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
22 changes: 14 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,10 @@ export default () => (
| dropdownAlign | additional align applied to dropdown | [AlignType](https://github.com/react-component/trigger/blob/728d7e92394aa4b3214650f743fc47e1382dfa68/src/interface.ts#L25-L80) | {} |
| dropdownMenuStyle | additional style applied to dropdown menu | Object | React.CSSProperties |
| notFoundContent | specify content to show when no result matches. | ReactNode | 'Not Found' |
| tokenSeparators | separator used to tokenize on tag/multiple mode | string[]? | |
| open | control select open | boolean | |
| defaultOpen | control select default open | boolean | |
| placeholder | select placeholder | React Node | |
| showSearch | whether show search input in single mode | boolean | true |
| showSearch | whether show search input in single mode | boolean \| Object | true |
| allowClear | whether allowClear | boolean | { clearIcon?: ReactNode } | false |
| tags | when tagging is enabled the user can select from pre-existing options or create a new tag by picking the first choice, which is what the user has typed into the search box so far. | boolean | false |
| tagRender | render custom tags. | (props: CustomTagProps) => ReactNode | - |
Expand All @@ -99,16 +98,11 @@ export default () => (
| combobox | enable combobox mode(can not set multiple at the same time) | boolean | false |
| multiple | whether multiple select | boolean | false |
| disabled | whether disabled select | boolean | false |
| filterOption | whether filter options by input value. default filter by option's optionFilterProp prop's value | boolean | true/Function(inputValue:string, option:Option) |
| optionFilterProp | which prop value of option will be used for filter if filterOption is true | String | 'value' |
| filterSort | Sort function for search options sorting, see [Array.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)'s compareFunction. | Function(optionA:Option, optionB: Option) | - |
| optionLabelProp | render option value or option children as content of select | String: 'value'/'children' | 'value' |
| defaultValue | initial selected option(s) | String \| String[] | - |
| value | current selected option(s) | String \| String[] \| {key:String, label:React.Node} \| {key:String, label:React.Node}[] | - |
| labelInValue | whether to embed label in value, see above value type. Not support `combobox` mode | boolean | false |
| backfill | whether backfill select option to search input (Only works in single and combobox mode) | boolean | false |
| onChange | called when select an option or input value change(combobox) | function(value, option:Option \| Option[]) | - |
| onSearch | called when input changed | function | - |
| onBlur | called when blur | function | - |
| onFocus | called when focus | function | - |
| onPopupScroll | called when menu is scrolled | function | - |
Expand All @@ -120,7 +114,6 @@ export default () => (
| getInputElement | customize input element | function(): Element | - |
| showAction | actions trigger the dropdown to show | String[]? | - |
| autoFocus | focus select after mount | boolean | - |
| autoClearSearchValue | auto clear search input value when multiple select is selected/deselected | boolean | true |
| prefix | specify the select prefix icon or text | ReactNode | - |
| suffixIcon | specify the select arrow icon | ReactNode | - |
| clearIcon | specify the clear icon | ReactNode | - |
Expand All @@ -141,6 +134,19 @@ export default () => (
| focus | focus select programmably | - | - |
| blur | blur select programmably | - | - |

### showSearch

| name | description | type | default |
| --- | --- | --- | --- |
| autoClearSearchValue | auto clear search input value when multiple select is selected/deselected | boolean | true |
| filterOption | whether filter options by input value. default filter by option's optionFilterProp prop's value | boolean | true/Function(inputValue:string, option:Option) |
| filterSort | Sort function for search options sorting, see [Array.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)'s compareFunction. | Function(optionA:Option, optionB: Option) | - |
| optionFilterProp | which prop value of option will be used for filter if filterOption is true | String | 'value' |
| optionLabelProp | render option value or option children as content of select | String: 'value'/'children' | 'value' |
| searchValue | The current input "search" text | string | - |
| tokenSeparators | separator used to tokenize on tag/multiple mode | string[]? | |
| onSearch | called when input changed | function | - |

### Option props

| name | description | type | default |
Expand Down
59 changes: 42 additions & 17 deletions src/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import type { FlattenOptionData } from './interface';
import { hasValue, isComboNoValue, toArray } from './utils/commonUtil';
import { fillFieldNames, flattenOptions, injectPropsWithOption } from './utils/valueUtil';
import warningProps, { warningNullOptions } from './utils/warningPropsUtil';
import useSearchConfig from './hooks/useSearchConfig';

const OMIT_DOM_PROPS = ['inputValue'];

Expand Down Expand Up @@ -110,35 +111,55 @@ type ArrayElementType<T> = T extends (infer E)[] ? E : T;

export type SemanticName = BaseSelectSemanticName;
export type PopupSemantic = 'listItem' | 'list';
export interface SearchConfig<OptionType> {
searchValue?: string;
autoClearSearchValue?: boolean;
onSearch?: (value: string) => void;
tokenSeparators?: string[];
filterOption?: boolean | FilterFunc<OptionType>;
filterSort?: (optionA: OptionType, optionB: OptionType, info: { searchValue: string }) => number;
optionFilterProp?: string;
optionLabelProp?: string;
}
export interface SelectProps<ValueType = any, OptionType extends BaseOptionType = DefaultOptionType>
extends BaseSelectPropsWithoutPrivate {
extends Omit<BaseSelectPropsWithoutPrivate, 'showSearch'> {
prefixCls?: string;
id?: string;

backfill?: boolean;

// >>> Field Names
fieldNames?: FieldNames;

searchValue?: string;
onSearch?: (value: string) => void;
showSearch?: boolean | SearchConfig<OptionType>;
/** @deprecated pleace use SearchConfig.searchValue */
searchValue?: SearchConfig<OptionType>['searchValue'];
/** @deprecated pleace use SearchConfig.autoClearSearchValue */
autoClearSearchValue?: boolean;

// >>> Select
onSelect?: SelectHandler<ArrayElementType<ValueType>, OptionType>;
onDeselect?: SelectHandler<ArrayElementType<ValueType>, OptionType>;
onActive?: (value: ValueType) => void;

/** @deprecated pleace use SearchConfig.onSearch */
onSearch?: SearchConfig<OptionType>['onSearch'];
/** @deprecated pleace use SearchConfig.tokenSeparators */
tokenSeparators?: string[];
// >>> Options
/**
* In Select, `false` means do nothing.
* In TreeSelect, `false` will highlight match item.
* It's by design.
*/
filterOption?: boolean | FilterFunc<OptionType>;
filterSort?: (optionA: OptionType, optionB: OptionType, info: { searchValue: string }) => number;
/** @deprecated pleace use SearchConfig.filterOption */
filterOption?: SearchConfig<OptionType>['filterOption'];
/** @deprecated pleace use SearchConfig.filterSort */
filterSort?: SearchConfig<OptionType>['filterSort'];
/** @deprecated pleace use SearchConfig.optionFilterProp */
optionFilterProp?: string;
/** @deprecated pleace use SearchConfig.optionLabelProp */
optionLabelProp?: string;

children?: React.ReactNode;
options?: OptionType[];
optionRender?: (
Expand Down Expand Up @@ -177,23 +198,13 @@ const Select = React.forwardRef<BaseSelectRef, SelectProps<any, DefaultOptionTyp
prefixCls = 'rc-select',
backfill,
fieldNames,

// Search
searchValue,
onSearch,
autoClearSearchValue = true,

showSearch,
// Select
onSelect,
onDeselect,
onActive,
popupMatchSelectWidth = true,

// Options
filterOption,
filterSort,
optionFilterProp,
optionLabelProp,
options,
optionRender,
children,
Expand All @@ -216,6 +227,18 @@ const Select = React.forwardRef<BaseSelectRef, SelectProps<any, DefaultOptionTyp
...restProps
} = props;

const [mergedShowSearch, searchConfig] = useSearchConfig(showSearch, props);
const {
filterOption,
searchValue,
optionFilterProp,
optionLabelProp,
filterSort,
onSearch,
autoClearSearchValue = true,
tokenSeparators,
} = searchConfig;

const mergedId = useId(id);
const multiple = isMultiple(mode);
const childrenAsData = !!(!options && children);
Expand Down Expand Up @@ -698,10 +721,12 @@ const Select = React.forwardRef<BaseSelectRef, SelectProps<any, DefaultOptionTyp
// >>> Trigger
direction={direction}
// >>> Search
showSearch={mergedShowSearch}
searchValue={mergedSearchValue}
onSearch={onInternalSearch}
autoClearSearchValue={autoClearSearchValue}
onSearchSplit={onInternalSearchSplit}
tokenSeparators={tokenSeparators}
popupMatchSelectWidth={popupMatchSelectWidth}
// >>> OptionList
OptionList={OptionList}
Expand Down
54 changes: 54 additions & 0 deletions src/hooks/useSearchConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { SearchConfig, DefaultOptionType } from '@/Select';
import * as React from 'react';
const legacySearchProps = [
'filterOption',
'searchValue',
'optionFilterProp',
'optionLabelProp',
'filterSort',
'onSearch',
'autoClearSearchValue',
'tokenSeparators',
];
// Convert `showSearch` to unique config
export default function useSearchConfig(
showSearch: boolean | SearchConfig<DefaultOptionType> | undefined,
props: any,
) {
const {
filterOption,
searchValue,
optionFilterProp,
optionLabelProp,
filterSort,
onSearch,
autoClearSearchValue,
tokenSeparators,
} = props || {};
return React.useMemo<[boolean | undefined, SearchConfig<DefaultOptionType>]>(() => {
const legacyShowSearch: SearchConfig<DefaultOptionType> = {};
legacySearchProps.forEach((name) => {
const val = props?.[name];
if (val !== undefined) legacyShowSearch[name] = val;
});
const searchConfig: SearchConfig<DefaultOptionType> =
typeof showSearch === 'object' ? showSearch : legacyShowSearch;
if (showSearch === undefined) {
return [undefined, searchConfig];
}
if (!showSearch) {
return [false, {}];
}
return [true, searchConfig];
}, [
showSearch,
filterOption,
searchValue,
optionFilterProp,
optionLabelProp,
filterSort,
onSearch,
autoClearSearchValue,
tokenSeparators,
]);
}
155 changes: 155 additions & 0 deletions tests/Select.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2521,4 +2521,159 @@ describe('Select.Basic', () => {
expect(input).toHaveClass(customClassNames.input);
expect(input).toHaveStyle(customStyle.input);
});
// searchValue?: string;
// autoClearSearchValue?: boolean;
// onSearch?: (value: string) => void;
// tokenSeparators?: string[];
// filterOption?: boolean | FilterFunc<OptionType>;
// filterSort?: (optionA: OptionType, optionB: OptionType, info: { searchValue: string }) => number;
// optionFilterProp?: string;
// optionLabelProp?: string;
// const props = {
// searchValue: '1',
// autoClearSearchValue: false,
// filterSort: (optionA, optionB) => {
// return Number(optionB.value) - Number(optionA.value);
// },
// optionFilterProp: 'label',
// optionLabelProp: 'value',
// };
describe('combine showSearch', () => {
let errorSpy;

beforeAll(() => {
errorSpy = jest.spyOn(console, 'error').mockImplementation(() => null);
});

beforeEach(() => {
errorSpy.mockReset();
resetWarned();
});

afterAll(() => {
errorSpy.mockRestore();
});
const currentSearchFn = jest.fn();
const legacySearchFn = jest.fn();

const LegacyDemo = (props) => {
return (
<Select
open
{...props}
options={[
{ value: 'a', label: '1' },
{ value: 'b', label: '2' },
{ value: 'c', label: '12' },
]}
/>
);
};
const CurrentDemo = (props) => {
return (
<Select
open
showSearch={props}
options={[
{ value: 'a', label: '1' },
{ value: 'b', label: '2' },
{ value: 'c', label: '12' },
]}
/>
);
};
it('onSearch', () => {
const { container } = render(
<>
<div id="test1">
<LegacyDemo onSearch={legacySearchFn} />
</div>
<div id="test2">
<CurrentDemo onSearch={currentSearchFn} />
</div>
</>,
);
const legacyInput = container.querySelector<HTMLInputElement>('#test1 input');
const currentInput = container.querySelector<HTMLInputElement>('#test2 input');
fireEvent.change(legacyInput, { target: { value: '2' } });
fireEvent.change(currentInput, { target: { value: '2' } });
expect(currentSearchFn).toHaveBeenCalledWith('2');
expect(legacySearchFn).toHaveBeenCalledWith('2');
});
it('searchValue', () => {
const { container } = render(
<>
<div id="test1">
<LegacyDemo searchValue="1" showSearch />
</div>
<div id="test2">
<CurrentDemo searchValue="1" />
</div>
</>,
);
const legacyInput = container.querySelector<HTMLInputElement>('#test1 input');
const currentInput = container.querySelector<HTMLInputElement>('#test2 input');
expect(legacyInput).toHaveValue('1');
expect(currentInput).toHaveValue('1');
expect(legacyInput.value).toBe(currentInput.value);
});
it('option:sort,FilterProp,LabelProp ', () => {
const { container } = render(
<>
<div id="test1">
<LegacyDemo
searchValue="2"
showSearch
filterSort={(a, b) => {
return Number(b.label) - Number(a.label);
}}
optionFilterProp="label"
optionLabelProp="value"
/>
</div>
<div id="test2">
<CurrentDemo
searchValue="2"
filterSort={(a, b) => {
return Number(b.label) - Number(a.label);
}}
optionFilterProp="label"
optionLabelProp="value"
/>
</div>
</>,
);
const items = container.querySelectorAll<HTMLDivElement>('.rc-select-item-option');
expect(items.length).toBe(4);
expect(items[0].title).toBe('12');
expect(items[2].title).toBe('12');
});
it('autoClearSearchValue,tokenSeparators', () => {
const { container } = render(
<>
<div id="test1">
<LegacyDemo showSearch autoClearSearchValue={false} tokenSeparators={[',', '*']} />
</div>
<div id="test2">
<CurrentDemo autoClearSearchValue={false} tokenSeparators={[',', '*']} />
</div>
</>,
);
const legacyInput = container.querySelector<HTMLInputElement>('#test1 input');
const currentInput = container.querySelector<HTMLInputElement>('#test2 input');
fireEvent.change(legacyInput, { target: { value: 'a' } });
fireEvent.change(currentInput, { target: { value: 'a' } });
expect(legacyInput).toHaveValue('a');
expect(currentInput).toHaveValue('a');
const items = container.querySelectorAll<HTMLDivElement>('.rc-select-item-option');
fireEvent.click(items[0]);
fireEvent.click(items[1]);
expect(legacyInput).toHaveValue('a');
expect(currentInput).toHaveValue('a');
fireEvent.change(legacyInput, { target: { value: '1,' } });
fireEvent.change(currentInput, { target: { value: '1,' } });
expect(legacyInput).toHaveValue('');
expect(currentInput).toHaveValue('');
});
});
});
Loading