2022-07-06 14:05:17 +00:00
|
|
|
import { Search } from 'react-feather';
|
|
|
|
import { useEffect, useMemo, useState } from 'react';
|
|
|
|
import _ from 'lodash';
|
|
|
|
|
2022-01-04 12:16:09 +00:00
|
|
|
import { useLocalStorage } from '@/portainer/hooks/useLocalStorage';
|
2022-07-06 14:05:17 +00:00
|
|
|
import { AutomationTestingProps } from '@/types';
|
2022-01-04 12:16:09 +00:00
|
|
|
|
2022-07-06 14:05:17 +00:00
|
|
|
interface Props extends AutomationTestingProps {
|
2022-01-04 12:16:09 +00:00
|
|
|
value: string;
|
2022-03-08 12:14:23 +00:00
|
|
|
placeholder?: string;
|
2022-01-04 12:16:09 +00:00
|
|
|
onChange(value: string): void;
|
|
|
|
}
|
|
|
|
|
2022-03-08 12:14:23 +00:00
|
|
|
export function SearchBar({
|
|
|
|
value,
|
|
|
|
placeholder = 'Search...',
|
|
|
|
onChange,
|
2022-07-06 14:05:17 +00:00
|
|
|
'data-cy': dataCy,
|
2022-03-08 12:14:23 +00:00
|
|
|
}: Props) {
|
2022-07-06 14:05:17 +00:00
|
|
|
const [searchValue, setSearchValue] = useDebounce(value, onChange);
|
|
|
|
|
2022-01-04 12:16:09 +00:00
|
|
|
return (
|
2022-07-06 14:05:17 +00:00
|
|
|
<div className="searchBar items-center flex">
|
|
|
|
<Search className="searchIcon feather" />
|
2022-01-04 12:16:09 +00:00
|
|
|
<input
|
|
|
|
type="text"
|
|
|
|
className="searchInput"
|
2022-07-06 14:05:17 +00:00
|
|
|
value={searchValue}
|
|
|
|
onChange={(e) => setSearchValue(e.target.value)}
|
2022-03-08 12:14:23 +00:00
|
|
|
placeholder={placeholder}
|
2022-07-06 14:05:17 +00:00
|
|
|
data-cy={dataCy}
|
2022-01-04 12:16:09 +00:00
|
|
|
/>
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-07-06 14:05:17 +00:00
|
|
|
function useDebounce(defaultValue: string, onChange: (value: string) => void) {
|
|
|
|
const [searchValue, setSearchValue] = useState(defaultValue);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setSearchValue(defaultValue);
|
|
|
|
}, [defaultValue]);
|
|
|
|
|
|
|
|
const onChangeDebounces = useMemo(
|
|
|
|
() => _.debounce(onChange, 300),
|
|
|
|
[onChange]
|
|
|
|
);
|
|
|
|
|
|
|
|
return [searchValue, handleChange] as const;
|
|
|
|
|
|
|
|
function handleChange(value: string) {
|
|
|
|
setSearchValue(value);
|
|
|
|
onChangeDebounces(value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-08 12:14:23 +00:00
|
|
|
export function useSearchBarState(
|
|
|
|
key: string
|
|
|
|
): [string, (value: string) => void] {
|
|
|
|
const filterKey = keyBuilder(key);
|
|
|
|
const [value, setValue] = useLocalStorage(filterKey, '', sessionStorage);
|
2022-01-04 12:16:09 +00:00
|
|
|
|
2022-03-08 12:14:23 +00:00
|
|
|
return [value, setValue];
|
2022-01-04 12:16:09 +00:00
|
|
|
|
2022-03-08 12:14:23 +00:00
|
|
|
function keyBuilder(key: string) {
|
|
|
|
return `datatable_text_filter_${key}`;
|
2022-01-04 12:16:09 +00:00
|
|
|
}
|
|
|
|
}
|