|
| 1 | +import React, { type FormEvent, useState } from "react"; |
| 2 | + |
| 3 | +import { DatePicker, InputGroup, ToolbarFilter } from "@patternfly/react-core"; |
| 4 | + |
| 5 | +import type { IFilterControlProps } from "./FilterControl"; |
| 6 | +import { |
| 7 | + americanDateFormat, |
| 8 | + isValidAmericanShortDate, |
| 9 | + parseAmericanDate, |
| 10 | +} from "./dateUtils"; |
| 11 | + |
| 12 | +export const DateFilter = <TItem,>({ |
| 13 | + category, |
| 14 | + filterValue, |
| 15 | + setFilterValue, |
| 16 | + showToolbarItem, |
| 17 | + isDisabled = false, |
| 18 | +}: React.PropsWithChildren< |
| 19 | + IFilterControlProps<TItem, string> |
| 20 | +>): React.JSX.Element | null => { |
| 21 | + const selectedFilters = filterValue ?? []; |
| 22 | + const validFilters = |
| 23 | + selectedFilters?.filter((value) => isValidAmericanShortDate(value)) ?? []; |
| 24 | + |
| 25 | + const [date, setDate] = useState<Date>(); |
| 26 | + |
| 27 | + // Update it if it changes externally |
| 28 | + React.useEffect(() => { |
| 29 | + if (filterValue?.[0]) { |
| 30 | + const date = parseAmericanDate(filterValue?.[0]); |
| 31 | + setDate(date); |
| 32 | + } else { |
| 33 | + setDate(undefined); |
| 34 | + } |
| 35 | + }, [filterValue]); |
| 36 | + |
| 37 | + const onDateChange = (_event: FormEvent<HTMLInputElement>, value: string) => { |
| 38 | + if (isValidAmericanShortDate(value)) { |
| 39 | + const newDate = parseAmericanDate(value); |
| 40 | + setDate(newDate); |
| 41 | + const target = americanDateFormat(newDate); |
| 42 | + if (target) { |
| 43 | + setFilterValue([target]); |
| 44 | + } |
| 45 | + } |
| 46 | + }; |
| 47 | + |
| 48 | + return ( |
| 49 | + <ToolbarFilter |
| 50 | + key={category.categoryKey} |
| 51 | + labels={validFilters.map((value) => ({ |
| 52 | + key: value, |
| 53 | + node: value, |
| 54 | + }))} |
| 55 | + deleteLabel={() => setFilterValue([])} |
| 56 | + categoryName={category.title} |
| 57 | + showToolbarItem={showToolbarItem} |
| 58 | + > |
| 59 | + <InputGroup> |
| 60 | + <DatePicker |
| 61 | + value={date ? americanDateFormat(date) : ""} |
| 62 | + dateFormat={americanDateFormat} |
| 63 | + dateParse={parseAmericanDate} |
| 64 | + onChange={onDateChange} |
| 65 | + aria-label="Date" |
| 66 | + placeholder="MM/DD/YYYY" |
| 67 | + // disable error text (no space in toolbar scenario) |
| 68 | + invalidFormatText={""} |
| 69 | + // default value ("parent") creates collision with sticky table header |
| 70 | + appendTo={document.body} |
| 71 | + isDisabled={isDisabled} |
| 72 | + /> |
| 73 | + </InputGroup> |
| 74 | + </ToolbarFilter> |
| 75 | + ); |
| 76 | +}; |
0 commit comments