Skip to content
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
37 changes: 37 additions & 0 deletions examples/singleFieldNames.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/* eslint-disable no-console */
import React from 'react';
import Select from '../src';
import '../assets/index.less';
import './single.less';

export default () => {
return (
<Select
style={{ width: 500 }}
onChange={console.log}
fieldNames={{
label: 'fieldLabel',
value: 'fieldValue',
options: 'fieldOptions',
}}
options={
[
{
fieldLabel: 'Group',
fieldOptions: [
{
fieldLabel: 'Bamboo',
fieldValue: 'bamboo',
},
{
fieldLabel: 'Light',
fieldValue: 'light',
},
],
},
] as any
}
/>
);
};
/* eslint-enable */
28 changes: 14 additions & 14 deletions src/OptionList.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';
import KeyCode from 'rc-util/lib/KeyCode';
import omit from 'rc-util/lib/omit';
import pickAttrs from 'rc-util/lib/pickAttrs';
import useMemo from 'rc-util/lib/hooks/useMemo';
import classNames from 'classnames';
Expand All @@ -12,13 +13,16 @@ import type {
OptionData,
RenderNode,
OnActiveValue,
FieldNames,
} from './interface';
import type { RawValueType, FlattenOptionsType } from './interface/generator';
import { fillFieldNames } from './utils/valueUtil';

export interface OptionListProps<OptionsType extends object[]> {
prefixCls: string;
id: string;
options: OptionsType;
fieldNames?: FieldNames;
flattenOptions: FlattenOptionsType<OptionsType>;
height: number;
itemHeight: number;
Expand Down Expand Up @@ -59,6 +63,7 @@ const OptionList: React.RefForwardingComponent<
{
prefixCls,
id,
fieldNames,
flattenOptions,
childrenAsData,
values,
Expand Down Expand Up @@ -246,7 +251,9 @@ const OptionList: React.RefForwardingComponent<
);
}

function renderItem(index: number) {
const omitFieldNameList = Object.values(fillFieldNames(fieldNames));

const renderItem = (index: number) => {
const item = memoFlattenOptions[index];
if (!item) return null;

Expand All @@ -266,7 +273,7 @@ const OptionList: React.RefForwardingComponent<
{value}
</div>
) : null;
}
};

return (
<>
Expand All @@ -287,8 +294,8 @@ const OptionList: React.RefForwardingComponent<
virtual={virtual}
onMouseEnter={onMouseEnter}
>
{({ group, groupOption, data }, itemIndex) => {
const { label, key } = data;
{({ group, groupOption, data, label, value }, itemIndex) => {
const { key } = data;

// Group
if (group) {
Expand All @@ -299,15 +306,8 @@ const OptionList: React.RefForwardingComponent<
);
}

const {
disabled,
value,
title,
children,
style,
className,
...otherProps
} = data as OptionData;
const { disabled, title, children, style, className, ...otherProps } = data as OptionData;
const passedProps = omit(otherProps, omitFieldNameList);

// Option
const selected = values.has(value);
Expand Down Expand Up @@ -337,7 +337,7 @@ const OptionList: React.RefForwardingComponent<

return (
<div
{...otherProps}
{...passedProps}
aria-selected={selected}
className={optionClassName}
title={optionTitle}
Expand Down
8 changes: 7 additions & 1 deletion src/generate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type { RefSelectorProps } from './Selector';
import Selector from './Selector';
import type { RefTriggerProps } from './SelectTrigger';
import SelectTrigger from './SelectTrigger';
import type { RenderNode, Mode, RenderDOMFunc, OnActiveValue } from './interface';
import type { RenderNode, Mode, RenderDOMFunc, OnActiveValue, FieldNames } from './interface';
import type {
GetLabeledValue,
FilterOptions,
Expand Down Expand Up @@ -84,6 +84,9 @@ export interface SelectProps<OptionsType extends object[], ValueType> extends Re
/** Config max length of input. This is only work when `mode` is `combobox` */
maxLength?: number;

// Field
fieldNames?: FieldNames;

// Search
inputValue?: string;
searchValue?: string;
Expand Down Expand Up @@ -276,6 +279,8 @@ export default function generateSelector<
autoClearSearchValue = true,
onSearch,

fieldNames,

// Icons
allowClear,
clearIcon,
Expand Down Expand Up @@ -961,6 +966,7 @@ export default function generateSelector<
open={mergedOpen}
childrenAsData={!options}
options={displayOptions}
fieldNames={fieldNames}
flattenOptions={displayFlattenOptions}
multiple={isMultiple}
values={rawValues}
Expand Down
8 changes: 3 additions & 5 deletions src/hooks/useCacheOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,16 @@ export default function useCacheOptions<
const optionMap = React.useMemo(() => {
const map: Map<RawValueType, FlattenOptionsType<OptionsType>[number]> = new Map();
options.forEach((item) => {
const {
data: { value },
} = item;
const { value } = item;
map.set(value, item);
});
return map;
}, [options]);

prevOptionMapRef.current = optionMap;

const getValueOption = (vals: RawValueType[]): FlattenOptionsType<OptionsType> =>
vals.map((value) => prevOptionMapRef.current.get(value)).filter(Boolean);
const getValueOption = (valueList: RawValueType[]): FlattenOptionsType<OptionsType> =>
valueList.map((value) => prevOptionMapRef.current.get(value)).filter(Boolean);

return getValueOption;
}
2 changes: 2 additions & 0 deletions src/interface/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ export declare function RefSelectFunc<OptionsType extends object[], ValueType>(
export type FlattenOptionsType<OptionsType extends object[] = object[]> = {
key: Key;
data: OptionsType[number];
label?: React.ReactNode;
value?: RawValueType;
/** Used for customize data */
[name: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any
}[];
8 changes: 8 additions & 0 deletions src/interface/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ export type RenderNode = React.ReactNode | ((props: any) => React.ReactNode);
export type Mode = 'multiple' | 'tags' | 'combobox';

// ======================== Option ========================
export interface FieldNames {
value?: string;
label?: string;
options?: string;
}

export type OnActiveValue = (
active: RawValueType,
index: number,
Expand Down Expand Up @@ -49,4 +55,6 @@ export interface FlattenOptionData {
groupOption?: boolean;
key: string | number;
data: OptionData | OptionGroupData;
label?: React.ReactNode;
value?: React.Key;
}
40 changes: 32 additions & 8 deletions src/utils/valueUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
OptionData,
OptionGroupData,
FlattenOptionData,
FieldNames,
} from '../interface';
import type {
LabelValueType,
Expand Down Expand Up @@ -32,32 +33,56 @@ function getKey(data: OptionData | OptionGroupData, index: number) {
return `rc-index-key-${index}`;
}

export function fillFieldNames(fieldNames?: FieldNames) {
const { label, value, options } = fieldNames || {};

return {
label: label || 'label',
value: value || 'value',
options: options || 'options',
};
}

/**
* Flat options into flatten list.
* We use `optionOnly` here is aim to avoid user use nested option group.
* Here is simply set `key` to the index if not provided.
*/
export function flattenOptions(options: SelectOptionsType): FlattenOptionData[] {
export function flattenOptions(
options: SelectOptionsType,
{ fieldNames }: { fieldNames?: FieldNames } = {},
): FlattenOptionData[] {
const flattenList: FlattenOptionData[] = [];

const {
label: fieldLabel,
value: fieldValue,
options: fieldOptions,
} = fillFieldNames(fieldNames);

function dig(list: SelectOptionsType, isGroupOption: boolean) {
list.forEach((data) => {
if (isGroupOption || !('options' in data)) {
const label = data[fieldLabel];

if (isGroupOption || !(fieldOptions in data)) {
// Option
flattenList.push({
key: getKey(data, flattenList.length),
groupOption: isGroupOption,
data,
label,
value: data[fieldValue],
});
} else {
// Option Group
flattenList.push({
key: getKey(data, flattenList.length),
group: true,
data,
label,
});

dig(data.options, true);
dig(data[fieldOptions], true);
}
});
}
Expand Down Expand Up @@ -94,11 +119,10 @@ export function findValueOption(
): OptionData[] {
const optionMap: Map<RawValueType, OptionData> = new Map();

options.forEach((flattenItem) => {
if (!flattenItem.group) {
const data = flattenItem.data as OptionData;
options.forEach(({ data, group, value }) => {
if (!group) {
// Check if match
optionMap.set(data.value, data);
optionMap.set(value, data as OptionData);
}
});

Expand All @@ -120,7 +144,7 @@ export function findValueOption(
export const getLabeledValue: GetLabeledValue<FlattenOptionData[]> = (
value,
{ options, prevValueMap, labelInValue, optionLabelProp },
) => {
): LabelValueType => {
const item = findValueOption([value], options)[0];
const result: LabelValueType = {
value,
Expand Down
79 changes: 79 additions & 0 deletions tests/Field.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/* eslint-disable import/no-named-as-default-member */
import { mount } from 'enzyme';
import { act } from 'react-dom/test-utils';
import * as React from 'react';
import Select from '../src';
import type { SelectProps } from '../src';
import { injectRunAllTimers } from './utils/common';

describe('Select.Field', () => {
injectRunAllTimers(jest);

beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

const OPTION_1 = { bambooLabel: 'Light', bambooValue: 'light' };
const OPTION_2 = { bambooLabel: 'Little', bambooValue: 'little' };

function mountSelect(props?: Partial<SelectProps<any>>) {
return mount(
<Select
open
options={
[
{
bambooLabel: 'Bamboo',
bambooChildren: [OPTION_1, OPTION_2],
},
] as any
}
fieldNames={{
label: 'bambooLabel',
value: 'bambooValue',
options: 'bambooChildren',
}}
{...props}
/>,
);
}

it('fieldNames should work', () => {
const onChange = jest.fn();
const onSelect = jest.fn();

const wrapper = mountSelect({ onChange, onSelect });

act(() => {
jest.runAllTimers();
});

// Label match
expect(wrapper.find('.rc-select-item-group').text()).toEqual('Bamboo');
expect(wrapper.find('.rc-select-item-option').first().text()).toEqual('Light');
expect(wrapper.find('.rc-select-item-option').last().text()).toEqual('Little');

// Click
wrapper.find('.rc-select-item-option-content').last().simulate('click');
expect(onChange).toHaveBeenCalledWith('little', OPTION_2);
expect(onSelect).toHaveBeenCalledWith('little', OPTION_2);
});

it('multiple', () => {
const onChange = jest.fn();
const wrapper = mountSelect({ mode: 'multiple', onChange });

// First one
wrapper.find('.rc-select-item-option-content').first().simulate('click');
expect(onChange).toHaveBeenCalledWith(['light'], [OPTION_1]);

// Last one
onChange.mockReset();
wrapper.find('.rc-select-item-option-content').last().simulate('click');
expect(onChange).toHaveBeenCalledWith(['light', 'little'], [OPTION_1, OPTION_2]);
});
});