59 lines
1.9 KiB
JavaScript
59 lines
1.9 KiB
JavaScript
// SearchBar.jsx
|
|
import React, { useEffect, useRef } from 'react';
|
|
import { FormControl, OutlinedInput, InputAdornment, IconButton, useTheme } from '@mui/material';
|
|
import SearchOutlined from '@mui/icons-material/SearchOutlined';
|
|
import ClearIcon from '@mui/icons-material/Clear';
|
|
|
|
const SearchBar = ({ value, onChange, sx, placeholder = 'Search (Ctrl + K)' }) => {
|
|
const theme = useTheme();
|
|
const inputRef = useRef(null);
|
|
|
|
/* ============================================= || handleKeyPress (CTRL + K) and ESC ||============================================= */
|
|
useEffect(() => {
|
|
const handleKeyPress = (event) => {
|
|
// Focus input with CTRL + K / CMD + K
|
|
if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
|
|
event.preventDefault();
|
|
inputRef.current?.focus();
|
|
}
|
|
|
|
// ESC removes focus
|
|
if (event.key === 'Escape' && document.activeElement === inputRef.current) {
|
|
inputRef.current.blur();
|
|
}
|
|
};
|
|
|
|
document.addEventListener('keydown', handleKeyPress);
|
|
return () => document.removeEventListener('keydown', handleKeyPress);
|
|
}, []);
|
|
|
|
return (
|
|
<FormControl fullWidth sx={{}}>
|
|
<OutlinedInput
|
|
inputRef={inputRef}
|
|
placeholder={placeholder}
|
|
sx={{
|
|
borderRadius: 0,
|
|
...sx
|
|
}}
|
|
value={value}
|
|
onChange={onChange}
|
|
autoComplete="off"
|
|
size="large"
|
|
startAdornment={
|
|
<InputAdornment position="start" sx={{ mr: -0.5, color: theme.palette.primary.main }}>
|
|
<SearchOutlined />
|
|
</InputAdornment>
|
|
}
|
|
endAdornment={
|
|
<IconButton sx={{ visibility: value ? 'visible' : 'hidden' }} onClick={() => onChange({ target: { value: '' } })}>
|
|
<ClearIcon style={{ fontSize: 'large', color: theme.palette.primary.main }} />
|
|
</IconButton>
|
|
}
|
|
/>
|
|
</FormControl>
|
|
);
|
|
};
|
|
|
|
export default SearchBar;
|