Skip to content
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

fix: reset combobox if no option selected onblur #2006

Merged
merged 3 commits into from
Aug 13, 2024
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
5 changes: 5 additions & 0 deletions .changeset/cold-meals-smile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontify/fondue-components": patch
---

fix: reset combobox if no option selected (onblur)
61 changes: 36 additions & 25 deletions packages/components/src/components/Select/Combobox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { IconCaretDown } from '@frontify/fondue-icons';
import * as RadixPopover from '@radix-ui/react-popover';
import { Slot as RadixSlot } from '@radix-ui/react-slot';
import { useCombobox } from 'downshift';
import { forwardRef, useMemo, useRef, type ForwardedRef, type ReactNode } from 'react';
import { type FocusEvent, forwardRef, useMemo, useRef, type ForwardedRef, type ReactNode } from 'react';

import { SelectMenu } from './SelectMenu';
import styles from './styles/select.module.scss';
Expand Down Expand Up @@ -61,66 +61,77 @@ export const SelectCombobox = (
const { inputSlots, menuSlots, items, filterText, clearButton, getItemByValue, setFilterText } =
useSelectData(children);

const defaultItem = getItemByValue(defaultValue);
const activeItem = getItemByValue(value);

const {
getInputProps,
getToggleButtonProps,
getMenuProps,
getItemProps,
reset,
selectedItem,
isOpen,
highlightedIndex,
inputValue,
} = useCombobox({
items,
selectedItem: getItemByValue(value),
defaultSelectedItem: getItemByValue(defaultValue),
defaultHighlightedIndex: 0,
onSelectedItemChange: ({ selectedItem }) => {
onSelect && onSelect(selectedItem.value);
},
selectedItem: activeItem,
onInputValueChange: ({ inputValue }) => {
setFilterText(inputValue);
},
defaultSelectedItem: defaultItem,
defaultHighlightedIndex: 0,
itemToString: (item) => (item ? item.label : ''),
});

const wasClicked = useRef(false);

const valueInvalid = useMemo(
() => inputValue && !items.find((item) => item.label.toLowerCase().includes(inputValue.toLowerCase())),
() => !items.find((item) => item.label.toLowerCase().includes(inputValue.toLowerCase())),
[inputValue, items],
);

const onBlurHandler = (blurEvent: FocusEvent<HTMLInputElement, Element>) => {
blurEvent.target.dataset.showFocusRing = 'false';
wasClicked.current = false;

const selectedItemNullOrOutdated = selectedItem?.label.toLocaleLowerCase() !== inputValue.toLocaleLowerCase();

if (selectedItemNullOrOutdated) {
// if there is no selection or
// the existing selected value is not the same as the input value (old),
// reset the input
reset();
}

if (getInputProps().onBlur) {
getInputProps().onBlur?.(blurEvent);
}
};

return (
<RadixPopover.Root open={isOpen}>
<RadixPopover.Anchor asChild>
<div ref={forwardedRef} className={styles.root} data-error={valueInvalid}>
<input
{...getInputProps({
'aria-label': ariaLabel,
})}
data-test-id={dataTestId}
placeholder={placeholder}
onBlur={onBlurHandler}
className={styles.input}
disabled={disabled}
onMouseDown={(mouseEvent) => {
wasClicked.current = true;
mouseEvent.currentTarget.dataset.showFocusRing = 'false';
}}
placeholder={placeholder}
{...getInputProps({
'aria-label': ariaLabel,
})}
onFocus={(focusEvent) => {
if (!wasClicked.current) {
focusEvent.target.dataset.showFocusRing = 'true';
}
}}
onBlur={(blurEvent) => {
blurEvent.target.dataset.showFocusRing = 'false';
wasClicked.current = false;
if (getInputProps().onBlur) {
getInputProps().onBlur?.(blurEvent);
}
}}
className={styles.input}
disabled={disabled}
data-test-id={dataTestId}
/>
{inputSlots}
{clearButton && (
Expand All @@ -136,13 +147,13 @@ export const SelectCombobox = (
</RadixSlot>
)}
<button
{...getToggleButtonProps()}
type="button"
aria-label="toggle menu"
disabled={disabled}
onMouseDown={() => {
wasClicked.current = true;
}}
{...getToggleButtonProps()}
aria-label="toggle menu"
disabled={disabled}
>
<IconCaretDown size={16} className={styles.caret} />
</button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as sinon from 'sinon';

import { Select } from '../Select';

const SELECT_TEST_ID = 'test-dropdown';
const SELECT_TEST_ID = 'test-combobox';
const GROUP_TEST_ID = 'test-group';
const ITEM_TEST_ID1 = 'test-item1';
const ITEM_TEST_ID2 = 'test-item2';
Expand Down Expand Up @@ -307,3 +307,28 @@ test('should render custom clear slot', async ({ mount, page }) => {
await expect(page.getByTestId(SLOT_CLEAR_TEST_ID)).toBeVisible();
await expect(component).toContainText('Clear Slot');
});

test('should clear input when typed value is not selected', async ({ mount, page }) => {
const component = await mount(
<Select.Combobox aria-label="test" data-test-id={SELECT_TEST_ID} placeholder={PLACEHOLDER_TEXT}>
<Select.Slot name="menu">
<Select.Item data-test-id={ITEM_TEST_ID1} value="test1">
{ITEM_TEXT1}
</Select.Item>
<Select.Item data-test-id={ITEM_TEST_ID2} value="test2">
{ITEM_TEXT2}
</Select.Item>
</Select.Slot>
</Select.Combobox>,
);

await expect(component).toBeVisible();
await component.click();

const nonExistentValue = 'test1';
await page.keyboard.type(nonExistentValue);
await page.keyboard.press('Tab');

await expect(component.getByTestId(SELECT_TEST_ID)).toHaveValue('');
await expect(page.getByPlaceholder(PLACEHOLDER_TEXT)).toBeVisible();
});
47 changes: 31 additions & 16 deletions packages/components/src/components/Select/useSelectData.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ export type SelectItemType = {
label: string;
};

/**
* Recursively extracts option values from children.
* This function traverses through the React component tree and collects all SelectItem values.
*
* @param {ReactNode} children - The React children to extract values from.
* @returns {SelectItemType[]} An array of SelectItemType objects.
*
* @example
* const options = (
* <SelectItem value="1">Option 1</SelectItem>
* <SelectItem value="2">Option 2</SelectItem>
* );
* const values = getRecursiveOptionValues(options);
* // Returns: [{ value: '1', label: 'Option 1' }, { value: '2', label: 'Option 2' }]
*/
export const getRecursiveOptionValues = (children: ReactNode): { value: string; label: string }[] => {
const values: { value: string; label: string }[] = [];
Children.forEach(children, (child) => {
Expand All @@ -27,12 +42,19 @@ export const getRecursiveOptionValues = (children: ReactNode): { value: string;
return values;
};

/**
* Custom hook for managing select data and filtering.
*
* @param {ReactNode} children - The React children to process, typically SelectItem components.
* @returns {Object} An object containing the processed data.
*/
export const useSelectData = (children: ReactNode) => {
const [filterText, setFilterText] = useState('');
const { inputSlots, menuSlots, itemValues, clearButton } = useMemo(() => {
const inputSlots: ReactNode[] = [];
const menuSlots: ReactNode[] = [];
let clearButton: ReactNode;

const hasSlots = Children.toArray(children).some(
(child) => isValidElement<SelectSlotProps>(child) && child.type === ForwardedRefSelectSlot,
);
Expand All @@ -53,23 +75,16 @@ export const useSelectData = (children: ReactNode) => {
}
}
});

return {
inputSlots,
menuSlots,
clearButton,
itemValues: getRecursiveOptionValues(menuSlots),
};
} else {
return {
menuSlots: children,
inputSlots: [],
itemValues: getRecursiveOptionValues(children),
};
menuSlots.push(children);
}

const itemValues = getRecursiveOptionValues(menuSlots);

return { inputSlots, menuSlots, itemValues, clearButton };
}, [children]);

const filteredItems = useMemo(
const items = useMemo(
() =>
itemValues.filter(
(item) => filterText === '' || item.label.toLowerCase().includes(filterText.toLowerCase()),
Expand All @@ -83,12 +98,12 @@ export const useSelectData = (children: ReactNode) => {
);

return {
inputSlots,
items,
menuSlots,
filterText,
inputSlots,
clearButton,
setFilterText,
filterText,
items: filteredItems,
getItemByValue,
};
};
Loading