Files
doormile_console_expresscopy/src/components/nearle_components/DebounceSearchBar.js
2026-05-13 17:48:36 +05:30

67 lines
1.9 KiB
JavaScript

/* eslint-disable react/prop-types */
import React, { useEffect, useRef } from 'react';
import { OutlinedInput, InputAdornment, Tooltip, IconButton } from '@mui/material';
import { SearchOutlined } from '@mui/icons-material';
import ClearIcon from '@mui/icons-material/Clear';
import { useDebounce } from 'use-debounce';
const DebounceSearchBar = ({
value,
onChange,
onDebouncedChange, // 🔹 NEW
debounceTime = 500,
placeholder = 'Search (ctrl+k)',
sx
}) => {
const textFieldRef = useRef(null);
const [debouncedValue] = useDebounce(value, debounceTime);
// fire debounced callback whenever debouncedValue changes
useEffect(() => {
if (onDebouncedChange) {
onDebouncedChange(debouncedValue);
}
}, [debouncedValue, onDebouncedChange]);
useEffect(() => {
const handleKeyPress = (event) => {
if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
textFieldRef.current?.focus();
}
if (event.key === 'Escape' && document.activeElement === textFieldRef.current) {
textFieldRef.current.blur();
}
};
document.addEventListener('keydown', handleKeyPress);
return () => document.removeEventListener('keydown', handleKeyPress);
}, []);
return (
<OutlinedInput
sx={{ ...sx }}
inputRef={textFieldRef}
placeholder={placeholder}
autoComplete="off"
value={value}
fullWidth
onChange={(e) => onChange(e.target.value)}
startAdornment={
<InputAdornment position="start" sx={{ mr: -0.5 }}>
<SearchOutlined />
</InputAdornment>
}
endAdornment={
<Tooltip title="Clear">
<IconButton sx={{ visibility: value ? 'visible' : 'hidden' }} onClick={() => onChange('')}>
<ClearIcon />
</IconButton>
</Tooltip>
}
/>
);
};
export default DebounceSearchBar;