Created
June 27, 2024 20:33
-
-
Save yurkimus/cfe48af25e7d622a86289f5bf2c43052 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRouter } from 'next/router'; | |
import { useCallback, useId } from 'react'; | |
import { FilterSegments, FilterTranslations } from '@/components/filters/filters.enumeration'; | |
import { Select } from '@/components/select/select'; | |
import { setSearchParams, stringify } from '@/utilities/methods'; | |
const Filters = Enumeration.of(['First', 'Second']) | |
const FilterSegments = Filters.fromKeys(['first', 'second']) | |
const FilterTranslations = Filters.fromKeys(['Первый', 'Второй']) | |
/** | |
* @typedef {object} Properties | |
* @prop {keyof typeof Filters[]} filters | |
* @prop {string} pathname | |
* @prop {URLSearchParams} searchParams | |
* @prop {Record<FiltersUnion, ComponentProps<'option'>[]>} context | |
* | |
* @param {Properties & ComponentProps<'ul'>} properties | |
*/ | |
export const SearchParamsFilters = ({ | |
className, | |
filters, | |
pathname, | |
searchParams, | |
context, | |
...properties | |
}) => { | |
let router = useRouter(); | |
let id = useId(); | |
let setFilters = useCallback( | |
/** | |
* @param {keyof typeof Filters} filter | |
* @param {string} value | |
* @param {URLSearchParams} searchParams | |
*/ | |
(filter, value, searchParams) => | |
router.replace( | |
pathname + | |
stringify( | |
URLSearchParams, | |
setSearchParams(FilterSegments[filter] + '=' + value, searchParams) | |
) | |
), | |
[] | |
); | |
return ( | |
<ul className={className} {...properties}> | |
{filters.map((filter, index) => ( | |
<li key={[id, 'li', index].join('-')}> | |
<Select | |
label={FilterTranslations[filter]} | |
value={searchParams.get(FilterSegments[filter])} | |
defaultValue="" | |
onChange={(event) => setFilters(filter, event.target.value, searchParams)} | |
> | |
{context[filter].map((properties, index) => ( | |
<option key={[id, 'option', index].join('-')} {...properties} /> | |
))} | |
</Select> | |
</li> | |
))} | |
</ul> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment