Skip to content

Commit

Permalink
feat: debounce the filtering to 100ms by default
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Jan 16, 2025
1 parent 1f58f4f commit 7f497fc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
20 changes: 17 additions & 3 deletions packages/core/src/useComboBox/useComboBox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { InputEvents, Reactivify, StandardSchema } from '../types';
import { Orientation } from '../types';
import {
createDescribedByProps,
debounce,
hasKeyCode,
isEqual,
normalizeProps,
Expand Down Expand Up @@ -91,8 +92,15 @@ export interface ComboBoxProps<TOption, TValue = TOption> {
}

export interface ComboBoxCollectionOptions {
/**
* The filter function to use.
*/
filter: FilterFn;
// collection?: CollectionManager<TOption>;

/**
* The debounce time in milliseconds for the filter function.
*/
debounceMs?: number;
}

export function useComboBox<TOption, TValue = TOption>(
Expand Down Expand Up @@ -313,7 +321,11 @@ export function useComboBox<TOption, TValue = TOption>(

const filter = collectionOptions?.filter;
if (filter) {
watch(inputValue, textValue => {
function updateHiddenState(textValue: string) {
if (!filter) {
return;
}

renderedOptions.value.forEach(opt => {
opt.setHidden(
!filter({
Expand All @@ -322,7 +334,9 @@ export function useComboBox<TOption, TValue = TOption>(
}),
);
});
});
}

watch(inputValue, debounce(collectionOptions?.debounceMs ?? 100, updateHiddenState));
}

return exposeField(
Expand Down
13 changes: 13 additions & 0 deletions packages/core/src/utils/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,3 +398,16 @@ export function fromNumberish(value: MaybeRefOrGetter<Numberish | undefined>): n

return Number.isNaN(num) ? undefined : num;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function debounce<TFunction extends (...args: any[]) => any>(ms: number, fn: TFunction) {
let timer: number | null = null;

return function (...args: Parameters<TFunction>) {
if (timer) {
clearTimeout(timer);
}

timer = window.setTimeout(() => fn(...args), ms);
};
}

0 comments on commit 7f497fc

Please sign in to comment.