import { InputHTMLAttributes, forwardRef, useState, useEffect, useRef, useCallback } from 'react';
import { Input } from './Input';
import { cn } from '@/lib/utils';
interface SearchInputProps extends Omit, 'onChange'> {
value?: string;
onChange?: (value: string) => void;
onDebouncedChange?: (value: string) => void;
debounceMs?: number;
placeholder?: string;
className?: string;
}
const SearchInput = forwardRef(
({
value = '',
onChange,
onDebouncedChange,
debounceMs = 300,
placeholder = "Rechercher...",
className,
...props
}, ref) => {
const [localValue, setLocalValue] = useState(value);
const timeoutRef = useRef(undefined);
// Fonction debouncée pour les changements
const debouncedChange = useCallback((searchValue: string) => {
if (timeoutRef.current) {
window.clearTimeout(timeoutRef.current);
}
timeoutRef.current = window.setTimeout(() => {
onDebouncedChange?.(searchValue);
}, debounceMs);
}, [onDebouncedChange, debounceMs]);
// Gérer les changements locaux
const handleChange = (e: React.ChangeEvent) => {
const newValue = e.target.value;
setLocalValue(newValue);
onChange?.(newValue);
debouncedChange(newValue);
};
// Synchroniser l'état local quand la valeur externe change
useEffect(() => {
setLocalValue(value);
}, [value]);
// Nettoyer le timeout au démontage
useEffect(() => {
return () => {
if (timeoutRef.current) {
window.clearTimeout(timeoutRef.current);
}
};
}, []);
return (
);
}
);
SearchInput.displayName = 'SearchInput';
export { SearchInput };