Skip to content

Commit

Permalink
feat(react-combobox): add useComboboxFilter() hook (microsoft#30046)
Browse files Browse the repository at this point in the history
  • Loading branch information
layershifter authored Jan 18, 2024
1 parent 1f067f9 commit 42b8015
Show file tree
Hide file tree
Showing 8 changed files with 132 additions and 43 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "minor",
"comment": "feat: add `useComboboxFilter()` hook",
"packageName": "@fluentui/react-combobox",
"email": "[email protected]",
"dependentChangeType": "patch"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "minor",
"comment": "feat: export `useComboboxFilter()` hook",
"packageName": "@fluentui/react-components",
"email": "[email protected]",
"dependentChangeType": "patch"
}
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,12 @@ export const useCombobox_unstable: (props: ComboboxProps, ref: React_2.Ref<HTMLI
// @public (undocumented)
export function useComboboxContextValues(state: ComboboxBaseState): ComboboxBaseContextValues;

// @public (undocumented)
export function useComboboxFilter<T extends {
children: React_2.ReactNode;
value: string;
} | string>(query: string, options: T[], config: UseComboboxFilterConfig<T>): JSX.Element[];

// @public
export const useComboboxStyles_unstable: (state: ComboboxState) => ComboboxState;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import * as React from 'react';
import { Option } from '../Option';

type UseComboboxFilterConfig<T extends { children: React.ReactNode; value: string } | string> = {
/** Provides a custom filter for the option. */
filter?: (optionText: string, query: string) => boolean;

/** Provides a custom message to display when there are no options. */
noOptionsMessage?: React.ReactNode;

/** Provides a way to map an option object to a React key. By default, "value" is used. */
optionToReactKey?: (option: T) => string;

/** Provides a way to map an option object to a text used for search. By default, "value" is used. */
optionToText?: (option: T) => string;

/** Provides a custom render for the option. */
renderOption?: (option: T) => JSX.Element;
};

function defaultFilter(optionText: string, query: string) {
if (query === '') {
return true;
}

return optionText.toLowerCase().includes(query.toLowerCase());
}

function defaultToString(option: string | { value: string }) {
return typeof option === 'string' ? option : option.value;
}

export function useComboboxFilter<T extends { children: React.ReactNode; value: string } | string>(
query: string,
options: T[],
config: UseComboboxFilterConfig<T>,
) {
const {
filter = defaultFilter,
noOptionsMessage = "We couldn't find any matches.",
optionToReactKey = defaultToString,
optionToText = defaultToString,

renderOption = (option: T) => {
if (typeof option === 'string') {
return <Option key={option}>{option}</Option>;
}

return (
<Option {...option} key={optionToReactKey(option)} text={optionToText(option)} value={option.value}>
{option.children}
</Option>
);
},
} = config;

const filteredOptions = React.useMemo(() => {
const searchValue = query.trim();

return options.filter(option => filter(optionToText(option), searchValue));
}, [options, optionToText, filter, query]);

if (filteredOptions.length === 0) {
return [
<Option aria-disabled="true" key="no-results" text="">
{noOptionsMessage}
</Option>,
];
}

return filteredOptions.map(option => renderOption(option));
}
2 changes: 2 additions & 0 deletions packages/react-components/react-combobox/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,5 @@ export {
} from './OptionGroup';
export type { OptionGroupProps, OptionGroupSlots, OptionGroupState } from './OptionGroup';
export type { OptionOnSelectData, SelectionEvents } from './Selection';

export { useComboboxFilter } from './hooks/useComboboxFilter';
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as React from 'react';
import { Combobox, makeStyles, Option, shorthands, useId } from '@fluentui/react-components';
import type { ComboboxProps } from '@fluentui/react-components';
import { Combobox, makeStyles, shorthands, useComboboxFilter, useId } from '@fluentui/react-components';

const useStyles = makeStyles({
root: {
Expand All @@ -13,50 +12,40 @@ const useStyles = makeStyles({
},
});

export const Filtering = (props: Partial<ComboboxProps>) => {
const comboId = useId('combo-default');
const options = [
'Cat',
'Caterpillar',
'Catfish',
'Cheetah',
'Chicken',
'Cockatiel',
'Cow',
'Dog',
'Dolphin',
'Ferret',
'Firefly',
'Fish',
'Fox',
'Fox Terrier',
'Frog',
'Hamster',
'Snake',
];
const [matchingOptions, setMatchingOptions] = React.useState([...options]);
const options = [
{ children: 'Alligator', value: 'Alligator' },
{ children: 'Bee', value: 'Bee' },
{ children: 'Bird', value: 'Bird' },
{ children: 'Cheetah', disabled: true, value: 'Cheetah' },
{ children: 'Dog', value: 'Dog' },
{ children: 'Dolphin', value: 'Dolphin' },
{ children: 'Ferret', value: 'Ferret' },
{ children: 'Firefly', value: 'Firefly' },
{ children: 'Fish', value: 'Fish' },
{ children: 'Goat', value: 'Goat' },
{ children: 'Horse', value: 'Horse' },
{ children: 'Lion', value: 'Lion' },
];

export const Filtering = () => {
const comboId = useId();
const styles = useStyles();

const onChange: ComboboxProps['onChange'] = event => {
const value = event.target.value.trim();
const matches = options.filter(option => option.toLowerCase().indexOf(value.toLowerCase()) === 0);
setMatchingOptions(matches);
};
const [query, setQuery] = React.useState<string>('');
const children = useComboboxFilter(query, options, {
noOptionsMessage: 'No animals match your search.',
});

return (
<div className={styles.root}>
<label id={comboId}>Best pet</label>
<Combobox aria-labelledby={comboId} placeholder="Select an animal" onChange={onChange} {...props}>
{matchingOptions.map(option => (
<Option key={option} disabled={option === 'Ferret'}>
{option}
</Option>
))}
{matchingOptions.length === 0 ? (
<Option key="no-results" text="">
No results found
</Option>
) : null}
<Combobox
aria-labelledby={comboId}
placeholder="Select an animal"
onChange={ev => setQuery(ev.target.value)}
value={query}
>
{children}
</Combobox>
</div>
);
Expand All @@ -65,9 +54,11 @@ export const Filtering = (props: Partial<ComboboxProps>) => {
Filtering.parameters = {
docs: {
description: {
story:
'Filtering based on the user-typed string can be achieved by modifying the child Options directly.' +
'We recommend implementing filtering when creating a freeform Combobox.',
story: `
We provide "useComboboxFilter()" hook to filter the options based on the user-typed string. It can be configured for a custom filter function, custom message, and custom render function.
We recommend using filtering when creating a freeform Combobox.
`.trim(),
},
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -1131,6 +1131,7 @@ import { useCheckmarkStyles_unstable } from '@fluentui/react-menu';
import { useColumnIdContext } from '@fluentui/react-table';
import { useCombobox_unstable } from '@fluentui/react-combobox';
import { useComboboxContextValues } from '@fluentui/react-combobox';
import { useComboboxFilter } from '@fluentui/react-combobox';
import { useComboboxStyles_unstable } from '@fluentui/react-combobox';
import { useCompoundButton_unstable } from '@fluentui/react-button';
import { useCompoundButtonStyles_unstable } from '@fluentui/react-button';
Expand Down Expand Up @@ -3678,6 +3679,8 @@ export { useCombobox_unstable }

export { useComboboxContextValues }

export { useComboboxFilter }

export { useComboboxStyles_unstable }

export { useCompoundButton_unstable }
Expand Down
1 change: 1 addition & 0 deletions packages/react-components/react-components/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@ export {
useComboboxContextValues,
ListboxProvider,
useListboxContextValues,
useComboboxFilter,
} from '@fluentui/react-combobox';
export type {
ComboboxProps,
Expand Down

0 comments on commit 42b8015

Please sign in to comment.