|
| 1 | +import type { FormEvent } from 'react'; |
| 2 | +import { useEffect, useState } from 'react'; |
| 3 | +import { ToolbarFilter } from '@patternfly/react-core'; |
| 4 | +import { useSearchParams } from 'react-router'; |
| 5 | +import { TextFilter } from '@console/internal/components/factory/text-filter'; |
| 6 | + |
| 7 | +type DataViewTextFilterProps = { |
| 8 | + title: string; |
| 9 | + filterId: string; |
| 10 | + placeholder: string; |
| 11 | + onChange?: (key: string, selectedValue: string) => void; |
| 12 | + showToolbarItem?: boolean; |
| 13 | +}; |
| 14 | + |
| 15 | +export const DataViewTextFilter = ({ |
| 16 | + title, |
| 17 | + filterId, |
| 18 | + placeholder, |
| 19 | + onChange, |
| 20 | + showToolbarItem, |
| 21 | +}: DataViewTextFilterProps) => { |
| 22 | + const [searchParams] = useSearchParams(); |
| 23 | + const [inputText, setInputText] = useState(searchParams.get(filterId) ?? ''); |
| 24 | + |
| 25 | + // Sync local state with URL changes |
| 26 | + useEffect(() => { |
| 27 | + setInputText(searchParams.get(filterId) ?? ''); |
| 28 | + }, [searchParams, filterId]); |
| 29 | + |
| 30 | + const handleChange = (_event: FormEvent<HTMLInputElement>, value: string) => { |
| 31 | + setInputText(value); |
| 32 | + onChange?.(filterId, value); |
| 33 | + }; |
| 34 | + |
| 35 | + const handleDeleteChip = () => { |
| 36 | + setInputText(''); |
| 37 | + onChange?.(filterId, ''); |
| 38 | + }; |
| 39 | + |
| 40 | + return ( |
| 41 | + <ToolbarFilter |
| 42 | + categoryName={title} |
| 43 | + showToolbarItem={showToolbarItem} |
| 44 | + labels={inputText ? [inputText] : []} |
| 45 | + deleteLabel={handleDeleteChip} |
| 46 | + > |
| 47 | + <TextFilter |
| 48 | + label={filterId} |
| 49 | + placeholder={placeholder} |
| 50 | + value={inputText} |
| 51 | + onChange={handleChange} |
| 52 | + /> |
| 53 | + </ToolbarFilter> |
| 54 | + ); |
| 55 | +}; |
0 commit comments