Skip to content

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 13 commits into
base: master
Choose a base branch
from
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export default () => (
| 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 +99,12 @@ 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 +116,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 +136,17 @@ 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\| (inputValue: string, option: Option) => boolean | true |
| 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' |
| searchValue | The current input "search" text | string | - |
| onSearch | called when input changed | function | - |

Comment on lines +139 to +149
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

缺失 tokenSeparators 属性文档
showSearch 小节中未列出 tokenSeparators 配置,建议同其他搜索相关属性一并文档化,以保持文档与实现一致。
示例 diff:

 ### showSearch

 | name                 | description                                                                | type                                            | default |
 | ---                  | ---                                                                        | ---                                             | ---     |
+| tokenSeparators      | 多选模式下用于分隔输入值并生成 tag 的分隔符数组                               | string[]                                        | -       |
 | autoClearSearchValue | auto-clear 搜索框中输入值,当多选模式下选中/取消选中会清空                     | boolean                                         | true    |
 | filterOption         | 是否根据输入值过滤选项;默认按 `optionFilterProp` 指定的属性过滤               | boolean \| (inputValue: string, option: Option) => boolean | true    |
 ...

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~143-~143: It appears that a hyphen is missing (if ‘auto’ is not used in the context of ‘cars’).
Context: ... | --- | --- | | autoClearSearchValue | auto clear search input value when multiple select...

(AUTO_HYPHEN)

🤖 Prompt for AI Agents
In README.md around lines 139 to 149, the showSearch section is missing
documentation for the tokenSeparators property. Add a new row in the table
describing tokenSeparators, including its name, description, type, and default
value, consistent with the style of other properties in this section to keep the
documentation complete and aligned with the implementation.

### Option props

| name | description | type | default |
Expand Down
50 changes: 34 additions & 16 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,18 +111,29 @@ 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;
filterOption?: boolean | FilterFunc<OptionType>;
filterSort?: (optionA: OptionType, optionB: OptionType, info: { searchValue: string }) => number;
optionFilterProp?: 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;
/** @deprecated pleace use SearchConfig.onSearch */
onSearch?: SearchConfig<OptionType>['onSearch'];
showSearch?: boolean | SearchConfig<OptionType>;
/** @deprecated pleace use SearchConfig.searchValue */
searchValue?: SearchConfig<OptionType>['searchValue'];
/** @deprecated pleace use SearchConfig.autoClearSearchValue */
autoClearSearchValue?: boolean;

// >>> Select
Expand All @@ -135,10 +147,14 @@ export interface SelectProps<ValueType = any, OptionType extends BaseOptionType
* 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;
optionLabelProp?: string;

children?: React.ReactNode;
options?: OptionType[];
optionRender?: (
Expand Down Expand Up @@ -177,22 +193,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,
Expand All @@ -216,6 +223,16 @@ const Select = React.forwardRef<BaseSelectRef, SelectProps<any, DefaultOptionTyp
...restProps
} = props;

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

const mergedId = useId(id);
const multiple = isMultiple(mode);
const childrenAsData = !!(!options && children);
Expand Down Expand Up @@ -698,6 +715,7 @@ const Select = React.forwardRef<BaseSelectRef, SelectProps<any, DefaultOptionTyp
// >>> Trigger
direction={direction}
// >>> Search
showSearch={mergedShowSearch}
searchValue={mergedSearchValue}
onSearch={onInternalSearch}
autoClearSearchValue={autoClearSearchValue}
Expand Down
48 changes: 48 additions & 0 deletions src/hooks/useSearchConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { SearchConfig, DefaultOptionType } from '@/Select';
import * as React from 'react';
const legacySearchProps = [
'filterOption',
'searchValue',
'optionFilterProp',
'filterSort',
'onSearch',
'autoClearSearchValue',
];
// Convert `showSearch` to unique config
export default function useSearchConfig(
showSearch: boolean | SearchConfig<DefaultOptionType> | undefined,
props: any,
) {
const {
filterOption,
searchValue,
optionFilterProp,
filterSort,
onSearch,
autoClearSearchValue,
} = 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,
filterSort,
onSearch,
autoClearSearchValue,
]);
}
133 changes: 133 additions & 0 deletions tests/Select.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2521,4 +2521,137 @@ describe('Select.Basic', () => {
expect(input).toHaveClass(customClassNames.input);
expect(input).toHaveStyle(customStyle.input);
});

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 ', () => {
const { container } = render(
<>
<div id="test1">
<LegacyDemo
searchValue="2"
showSearch
filterSort={(a, b) => {
return Number(b.label) - Number(a.label);
}}
optionFilterProp="label"
/>
</div>
<div id="test2">
<CurrentDemo
searchValue="2"
filterSort={(a, b) => {
return Number(b.label) - Number(a.label);
}}
optionFilterProp="label"
/>
</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', () => {
const { container } = render(
<>
<div id="test1">
<LegacyDemo showSearch autoClearSearchValue={false} />
</div>
<div id="test2">
<CurrentDemo autoClearSearchValue={false} />
</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');
});
});
});
Loading