diff --git a/containers/ecr-viewer/src/app/components/BaseFilter.tsx b/containers/ecr-viewer/src/app/components/BaseFilter.tsx index 8a8e93d7c..2dce64cc0 100644 --- a/containers/ecr-viewer/src/app/components/BaseFilter.tsx +++ b/containers/ecr-viewer/src/app/components/BaseFilter.tsx @@ -1,6 +1,14 @@ -import React, { ComponentType, ReactNode, useCallback, useState } from "react"; +import React, { + ComponentType, + ReactNode, + useCallback, + useContext, + useEffect, + useRef, +} from "react"; import { Button } from "@trussworks/react-uswds"; import { useRouter, usePathname, useSearchParams } from "next/navigation"; +import { FILTER_CLOSED, FILTER_SUBMITTED, FilterOpenContext } from "./Filters"; /** * Custom hook to manage query parameters in the URL (set, delete, and update). Hook always resets page back to 1. @@ -94,11 +102,33 @@ export const Filter = ({ submitHandler: () => void; children: ReactNode; }) => { - const [isFilterBoxOpen, setIsFilterBoxOpen] = useState(false); - const openBtnRef = React.useRef(null); + const { filterBoxOpen, setFilterBoxOpen, lastOpenButtonRef } = + useContext(FilterOpenContext); + const openBtnRef = useRef(null); + + const isFilterBoxOpen = filterBoxOpen === type; + const setIsFilterBoxOpen = useCallback((open: boolean) => { + if (open) { + setFilterBoxOpen(type); + // Set the last open button to this button when we open it + lastOpenButtonRef.current = openBtnRef.current?.parentElement || null; + } else { + setFilterBoxOpen(FILTER_CLOSED); + } + openBtnRef?.current?.parentElement?.focus(); + }, []); + + // This filter has closed. We need the special submitted case to prevent + // a race condition with submitting and resetting if we try to do a reset + // just after submitting. + useEffect(() => { + if (filterBoxOpen !== FILTER_SUBMITTED && filterBoxOpen !== type) { + resetHandler(); + } + }, [filterBoxOpen]); return ( -
+
e.stopPropagation()}>