import { omit } from 'lodash' ; import { useHistory } from 'react-router-dom' ; import { uxFiltersByName , UxLocalUIFilter , UxLocalUIFilterName , } from '../../../../../common/ux_ui_filter' ; import { fromQuery , toQuery , } from '../../../../components/shared/links/url_helpers' ; import { removeUndefinedProps } from '../../../../context/url_params_context/helpers' ; import { useLegacyUrlParams } from '../../../../context/url_params_context/use_url_params' ; import { getExcludedName } from '../local_ui_filters' ; export type FiltersUIHook = ReturnType < typeof useLocalUIFilters > ; export function useLocalUIFilters ( { filterNames , } ) { const history = useHistory ( ) ; const { uxUiFilters } = useLegacyUrlParams ( ) ; const setFilterValue = ( name , value ) => { const search = omit ( toQuery ( history . location . search ) , name ) ; history . push ( { ... history . location , search : fromQuery ( removeUndefinedProps ( { ... search , [ name ] : value . length ? value . join ( ',' ) : undefined , } ) ) , } ) ; } ; const invertFilter = ( name , value , negate ) => { if ( ! negate ) { setFilterValue ( name , ( uxUiFilters ?. [ name ] as string [ ] ) . filter ( ( valT ) => valT !== value ) ) ; const excludedName = getExcludedName ( name ) ; setFilterValue ( excludedName , [ ... ( uxUiFilters ?. [ excludedName ] ?? [ ] ) , value , ] ) ; } else { const includeName = name . split ( 'Excluded' ) [ 0 ] as UxLocalUIFilterName ; const excludedName = name ; setFilterValue ( excludedName , ( uxUiFilters ?. [ excludedName ] as string [ ] ) . filter ( ( valT ) => valT !== value ) ) ; setFilterValue ( includeName , [ ... ( uxUiFilters ?. [ includeName ] ?? [ ] ) , value , ] ) ; } } ; const clearValues = ( ) => { const search = omit ( toQuery ( history . location . search ) , [ ... filterNames , 'searchTerm' , 'transactionUrl' , ] ) ; history . push ( { ... history . location , search : fromQuery ( search ) , } ) ; } ; const filters = filterNames . map ( ( name ) => ( { value : ( uxUiFilters [ name ] as string [ ] ) ?? [ ] , ... uxFiltersByName [ name ] , name , } ) ) ; return { filters , setFilterValue , clearValues , invertFilter , } ; }