Skip to content
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
104 changes: 104 additions & 0 deletions packages/vkui/src/components/CustomSelect/CustomSelect.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1986,4 +1986,108 @@ describe('CustomSelect', () => {
// дропдаун открыт вниз и класс для границ выставлен верно
expect(document.querySelector(`.${styles.popDown}`)).not.toBeNull();
});

describe('searchable + allowClearButton', () => {
it('shows clear button when typing in search and hides when search is empty', async () => {
render(
<CustomSelect
searchable
allowClearButton
labelTextTestId="labelTextTestId"
clearButtonTestId="clearButtonTestId"
options={[
{ value: 0, label: 'Mike' },
{ value: 1, label: 'Josh' },
]}
slotProps={{
input: {
'data-testid': INPUT_TEST_ID,
},
}}
/>,
);

// дропдаун закрыт — кнопки очистки нет
expect(screen.queryByTestId('clearButtonTestId')).toBeFalsy();

// открываем дропдаун и вводим текст
fireEvent.click(screen.getByTestId('labelTextTestId'));
await waitFor(() => expect(screen.getByTestId(INPUT_TEST_ID)).toHaveFocus());
expect(screen.queryByTestId('clearButtonTestId')).toBeFalsy();

fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: 'Mi' } });
expect(getInputValue()).toBe('Mi');
expect(screen.getByTestId('clearButtonTestId')).toBeTruthy();

// очищаем поле поиска — кнопка снова пропадает
fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: '' } });
expect(screen.queryByTestId('clearButtonTestId')).toBeFalsy();
});

it('clicking clear button clears only search text and keeps selected value', async () => {
const onChange = vi.fn();

render(
<CustomSelect
searchable
allowClearButton
labelTextTestId="labelTextTestId"
clearButtonTestId="clearButtonTestId"
options={[
{ value: 0, label: 'Mike' },
{ value: 1, label: 'Josh' },
]}
defaultValue={0}
onChange={onChange}
slotProps={{
input: {
'data-testid': INPUT_TEST_ID,
},
}}
/>,
);

expect(getCustomSelectValue()).toEqual('Mike');

// открываем дропдаун и вводим текст
fireEvent.click(screen.getByTestId('labelTextTestId'));
await waitFor(() => expect(screen.getByTestId(INPUT_TEST_ID)).toHaveFocus());
fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: 'Jo' } });
expect(getInputValue()).toBe('Jo');

// кликаем по кнопке очистки
fireEvent.click(screen.getByTestId('clearButtonTestId'));

// текст поиска сброшен
expect(getInputValue()).toBe('');
// выбранное значение сохраняется
expect(getCustomSelectValue()).toEqual('Mike');
// onChange не вызывается — выбранное значение не менялось
expect(onChange).not.toHaveBeenCalled();
});

it('does not show clear button without allowClearButton when typing in search', async () => {
render(
<CustomSelect
searchable
labelTextTestId="labelTextTestId"
options={[
{ value: 0, label: 'Mike' },
{ value: 1, label: 'Josh' },
]}
slotProps={{
input: {
'data-testid': INPUT_TEST_ID,
},
}}
/>,
);

fireEvent.click(screen.getByTestId('labelTextTestId'));
await waitFor(() => expect(screen.getByTestId(INPUT_TEST_ID)).toHaveFocus());
fireEvent.change(screen.getByTestId(INPUT_TEST_ID), { target: { value: 'Mi' } });

expect(screen.queryByRole('button', { hidden: true })).toBeFalsy();
});
});
});
6 changes: 6 additions & 0 deletions packages/vkui/src/components/CustomSelect/CustomSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,12 @@ export function CustomSelect<OptionInterfaceT extends CustomSelectOptionInterfac
disabled: inputRest.disabled,
readOnly,
icon: iconProp,
searchable,
inputValue,
onInputClear: () => {
resetInputValue();
selectInputRef.current && selectInputRef.current.focus();
},
});

const passClickAndFocusToInputOnClick = React.useCallback(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ interface UseAfterItemsProps
nativeSelectValue: NativeSelectValue;
opened: boolean;
onClearButtonClick: () => void;
searchable: boolean;
inputValue: string;
onInputClear: () => void;
}
/* eslint-enable jsdoc/require-jsdoc */

Expand All @@ -39,28 +42,43 @@ export function useAfterItems({
disabled,
readOnly,
icon: iconProp,
searchable,
inputValue,
onInputClear,
}: UseAfterItemsProps) {
const onClearButtonClickCb = useStableCallback(onClearButtonClick);
const onInputClearCb = useStableCallback(onInputClear);

const controlledValueSet = isControlledOutside && value !== NOT_SELECTED.CUSTOM;
const uncontrolledValueSet = !isControlledOutside && nativeSelectValue !== NOT_SELECTED.NATIVE;
const clearButtonShown =
allowClearButton && !opened && (controlledValueSet || uncontrolledValueSet);
const valueSet = controlledValueSet || uncontrolledValueSet;
const hasInputValue = searchable && opened && inputValue.length > 0;
const clearButtonShown = allowClearButton && !opened && valueSet;
const inputClearButtonShown = allowClearButton && hasInputValue;

const clearButton = React.useMemo(() => {
if (!clearButtonShown) {
if (!clearButtonShown && !inputClearButtonShown) {
return null;
}

return (
<ClearButton
className={iconProp === undefined ? styles.clearIcon : undefined}
onClick={onClearButtonClickCb}
onClick={inputClearButtonShown ? onInputClearCb : onClearButtonClickCb}
disabled={disabled}
data-testid={clearButtonTestId}
/>
);
}, [clearButtonShown, ClearButton, iconProp, onClearButtonClickCb, disabled, clearButtonTestId]);
}, [
clearButtonShown,
inputClearButtonShown,
ClearButton,
iconProp,
onInputClearCb,
onClearButtonClickCb,
disabled,
clearButtonTestId,
]);

const icon = React.useMemo(() => {
if (iconProp !== undefined) {
Expand All @@ -69,21 +87,21 @@ export function useAfterItems({

return (
<DropdownIcon
className={clearButtonShown ? styles.dropdownIcon : undefined}
className={clearButtonShown || inputClearButtonShown ? styles.dropdownIcon : undefined}
opened={opened}
/>
);
}, [clearButtonShown, iconProp, opened]);
}, [clearButtonShown, inputClearButtonShown, iconProp, opened]);

return React.useMemo(
() =>
!readOnly &&
(icon || clearButtonShown) && (
(icon || clearButtonShown || inputClearButtonShown) && (
<React.Fragment>
{clearButton}
{icon}
</React.Fragment>
),
[clearButton, clearButtonShown, icon, readOnly],
[clearButton, clearButtonShown, inputClearButtonShown, icon, readOnly],
);
}
Loading