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

ComboBox filter reset behavior (clearFilterOnOptionToggle) #2294

Merged
merged 18 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from 12 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/sharp-islands-vanish.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@itwin/itwinui-react': minor
---

`ComboBox` with `multiple` enabled now offers a `clearFilterOnOptionToggle` prop to control whether the filter is cleared or not when an option is toggled. The default multi select `ComboBox` behavior is unchanged since the default prop value is `true`.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
35 changes: 25 additions & 10 deletions apps/react-workshop/src/ComboBox.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import {
SelectOption,
MenuItemSkeleton,
InputGrid,
Flex,
Checkbox,
Divider,
} from '@itwin/itwinui-react';
import { SvgCamera } from '@itwin/itwinui-icons-react';
import { StoryDefault } from '@ladle/react';
Expand Down Expand Up @@ -519,16 +522,28 @@ export const MultipleSelect = () => {
'AX',
]);

const [clearFilterOnOptionToggle, setClearFilterOnOptionToggle] =
React.useState(true);

return (
<ComboBox
options={options}
inputProps={{ placeholder: 'Select a country' }}
multiple
value={selectedOptions}
onChange={(selected, event) => {
console.log(event.value + ' ' + event.type);
setSelectedOptions(selected);
}}
/>
<Flex flexDirection='column' alignItems='stretch'>
<Checkbox
checked={clearFilterOnOptionToggle}
onChange={(e) => setClearFilterOnOptionToggle(e.target.checked)}
label='clearFilterOnOptionToggle'
/>
<Divider />
<ComboBox
options={options}
inputProps={{ placeholder: 'Select a country' }}
multiple
value={selectedOptions}
onChange={(selected, event) => {
console.log(event.value + ' ' + event.type);
setSelectedOptions(selected);
}}
clearFilterOnOptionToggle={clearFilterOnOptionToggle}
/>
</Flex>
);
};
2 changes: 1 addition & 1 deletion apps/react-workshop/src/ComboBox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ describe('ComboBox', () => {
const id = Cypress.storyId(storyPath, testName);
cy.visit('/', { qs: { mode: 'preview', story: id } });
cy.compareSnapshot(`${testName} (Closed)`);
cy.get('input').focus();
cy.get('[role=combobox]').focus();
if (testName === 'Multiple Select') {
cy.get('[role=option]').then((els) => {
const items = Array.from(els, (el) => el);
Expand Down
5 changes: 5 additions & 0 deletions apps/website/src/content/docs/combobox.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ Set the property `multiple` to true to allow users to select more than one value
<AllExamples.ComboBoxMultipleSelectExample client:load />
</LiveExample>

When `multiple` is `true`, a `clearFilterOnOptionToggle` prop is available. Possible values:

- `true` (default): Filter is cleared when an option is toggled. Useful when users would likely want to re-filter after toggling an option.
- `false`: Filter is _not_ cleared when an option is toggled. This is useful when users would likely want to toggle multiple options from the same filtered results.

### Virtualized

If you expect the combobox to have a very long list of items, you can set `enableVirtualization` to true. This will use virtualization for the scrollable dropdown list.
Expand Down
31 changes: 24 additions & 7 deletions packages/itwinui-react/src/core/ComboBox/ComboBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,25 @@ export type ComboboxMultipleTypeProps<T> =
* Callback fired when selected value changes.
*/
onChange?: (value: T) => void;
/**
* Only applicable when `multiple` is enabled.
*
* If `true`, toggling an option will clear the filter.
* Useful when users would likely want to re-filter after toggling an option.
*
* If `false`, the filter will remain as-is after toggling an option.
* Useful when users would likely want to toggle multiple options from the _same_ filtered results.
*
* @default true
*/
clearFilterOnOptionToggle?: never;
}
| {
multiple: true;
value?: T[] | null | undefined;
defaultValue?: T[] | null;
onChange?: (value: T[], event: MultipleOnChangeProps<T>) => void;
clearFilterOnOptionToggle?: boolean;
};

export type ComboBoxProps<T> = {
Expand Down Expand Up @@ -212,6 +225,7 @@ export const ComboBox = React.forwardRef(
onHide: onHideProp,
id = inputProps?.id ? `iui-${inputProps.id}-cb` : idPrefix,
defaultValue,
clearFilterOnOptionToggle = true,
...rest
} = props;

Expand Down Expand Up @@ -457,7 +471,6 @@ export const ComboBox = React.forwardRef(
return;
}

setIsInputDirty(false);
if (multiple) {
const actionType = isMenuItemSelected(__originalIndex)
? 'removed'
Expand All @@ -481,22 +494,26 @@ export const ComboBox = React.forwardRef(
.join(', '),
);

// Clear the filter whenever an item is selected
setInputValue('');
// If clearFilterOnOptionToggle, clear the filter
setIsInputDirty(!clearFilterOnOptionToggle);
if (clearFilterOnOptionToggle) {
setInputValue('');
}
} else {
setSelectedIndexes(__originalIndex);
hide();
onChangeHandler(__originalIndex);
}
},
[
selectedChangeHandler,
isMenuItemSelected,
optionsRef,
multiple,
isMenuItemSelected,
selectedChangeHandler,
setSelectedIndexes,
onChangeHandler,
optionsRef,
clearFilterOnOptionToggle,
hide,
setSelectedIndexes,
],
);

Expand Down
7 changes: 7 additions & 0 deletions testing/e2e/app/routes/ComboBox/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const Default = ({
options,
showChangeValueButton,
virtualization,
clearFilterOnOptionToggle,
} = config;
const [value, setValue] = React.useState(initialValue);

Expand All @@ -39,6 +40,7 @@ const Default = ({
value={value as any}
multiple={multiple}
enableVirtualization={virtualization}
clearFilterOnOptionToggle={clearFilterOnOptionToggle as any}
/>
</div>
);
Expand All @@ -52,6 +54,10 @@ function getConfigFromSearchParams() {
const exampleType = searchParams.get('exampleType') as 'default' | undefined;
const virtualization = searchParams.get('virtualization') === 'true';
const multiple = searchParams.get('multiple') === 'true';
const clearFilterOnOptionToggle =
searchParams.get('clearFilterOnOptionToggle') != null
? searchParams.get('clearFilterOnOptionToggle') === 'true'
: undefined;
const showChangeValueButton =
searchParams.get('showChangeValueButton') === 'true';

Expand Down Expand Up @@ -82,5 +88,6 @@ function getConfigFromSearchParams() {
showChangeValueButton,
options,
initialValue,
clearFilterOnOptionToggle,
};
}
86 changes: 47 additions & 39 deletions testing/e2e/app/routes/ComboBox/spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,44 +74,6 @@ test('should select multiple options', async ({ page }) => {
});
});

test(`should clear filter and input value when an option is toggled and when focus is lost (multiple=true)`, async ({
page,
}) => {
await page.goto(`/ComboBox?multiple=true`);

const options = page.getByRole('option');
const input = page.locator('input');

await input.focus();
await input.fill('1');

await expect(options).toHaveCount(3);
await expect(input).toHaveValue('1');

await options.first().click();

// Should clear filter when an option is toggled
await expect(options).not.toHaveCount(3);
await expect(input).toHaveValue('');

await input.fill('1');

await expect(options).toHaveCount(3);
await expect(input).toHaveValue('1');

await page.keyboard.press('Tab');

// Should clear filter when focus is lost
await expect(options).toHaveCount(0);
await expect(input).toHaveValue('');

await input.focus();

// Should not be filtered the next time the menu is opened
await expect(options).toHaveCount(defaultOptions.length);
await expect(input).toHaveValue('');
});

test(`should clear filter and set input value when an option is toggled and when focus is lost (multiple=false)`, async ({
page,
}) => {
Expand Down Expand Up @@ -153,6 +115,52 @@ test(`should clear filter and set input value when an option is toggled and when
await expect(input).toHaveValue('Item 1');
});

[false, true, undefined].map((clearFilterOnOptionToggle) => {
test(`should support clearFilterOnOptionToggle=${clearFilterOnOptionToggle} (multiple=true)`, async ({
page,
}) => {
const clearFilterOnOptionToggleQueryParam =
clearFilterOnOptionToggle != null
? `&clearFilterOnOptionToggle=${clearFilterOnOptionToggle}`
: '';

await page.goto(
'/ComboBox?multiple=true' + clearFilterOnOptionToggleQueryParam,
);

const options = page.locator('[role="option"]');
const input = page.locator('input');

await input.fill('1');
await expect(options).toHaveCount(3);

await options.first().click();

if (clearFilterOnOptionToggle !== false) {
await expect(input).toHaveValue('');
await expect(options).not.toHaveCount(3);
} else {
await expect(input).toHaveValue('1');
await expect(options).toHaveCount(3);
}

await expect(page.locator('[role=option][aria-selected=true]')).toHaveCount(
1,
);

await input.fill('1');

await expect(options).toHaveCount(3);
await expect(input).toHaveValue('1');

await page.keyboard.press('Tab');

// Regardless of clearFilterOnOptionToggle, the filter should be cleared when focus is lost
await expect(options).toHaveCount(0);
await expect(input).toHaveValue('');
});
});

test.describe('ComboBox (virtualization)', () => {
test('should support keyboard navigation when virtualization is enabled', async ({
page,
Expand Down Expand Up @@ -229,7 +237,7 @@ test.describe('ComboBox (virtualization)', () => {

//Filter and focus first
await comboBoxInput.fill('1');
expect(items).toHaveCount(3);
await expect(items).toHaveCount(3);
await page.keyboard.press('ArrowDown');
await expect(comboBoxInput).toHaveAttribute(
'aria-activedescendant',
Expand Down
Loading