-
Notifications
You must be signed in to change notification settings - Fork 14
/
filter.tsx
111 lines (94 loc) · 2.54 KB
/
filter.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import { createContext, useContext, useEffect, useState } from 'react'
import { useLocation, useMatch, useNavigate } from 'react-router-dom'
import { getPath } from '../constants'
import { disableSortByTrending } from '../pages/landing/filters/sort'
import {
ActivityResourceType,
ProjectsOrderByInput,
ProjectStatus,
ProjectType,
} from '../types'
import { toInt } from '../utils'
export type FilterType = {
countryCode?: string
region?: string
search?: string
status?: ProjectStatus
type?: ProjectType
tagIds?: number[]
recent?: boolean
activity?: ActivityResourceType
}
export type SortType = { recent?: boolean } & ProjectsOrderByInput
export interface FilterState {
filters: FilterType
updateFilter: (value: Partial<FilterType>) => void
sort: SortType
updateSort: (value: Partial<SortType>) => void
clearFilter: () => void
}
const defaultFilterContext = {
filters: {},
updateFilter() {},
sort: {},
updateSort() {},
clearFilter() {},
}
const defaultSort = { createdAt: 'desc' } as SortType
export const FilterContext = createContext<FilterState>(defaultFilterContext)
export const FilterProvider = ({
children,
isLoggedIn,
}: {
children: React.ReactNode
isLoggedIn?: boolean
}) => {
const [filters, setFilters] = useState<FilterType>({} as FilterType)
const [sort, setSort] = useState<SortType>(defaultSort)
const isLandingFeedPage = useMatch(getPath('landingFeed'))
const location = useLocation()
const navigate = useNavigate()
const updateFilter = (value: Partial<FilterType>) => {
if (isLandingFeedPage && !isLoggedIn) {
navigate('/', { state: { save: true } })
}
setFilters({ ...filters, recent: false, ...value })
}
useEffect(() => {
if (sort.recent) {
if (disableSortByTrending(filters)) {
setSort(defaultSort)
}
}
}, [filters, sort])
useEffect(() => {
if (location.state?.tagId) {
updateFilter({ tagIds: [toInt(location.state?.tagId)] })
navigate('', { state: null })
} else if (location.state?.save) {
navigate('', { state: null })
} else {
setFilters({})
}
}, [location.pathname])
const updateSort = (value: Partial<SortType>) => {
setSort({ ...value })
}
const clearFilter = () => {
setFilters({} as FilterType)
}
return (
<FilterContext.Provider
value={{
filters,
updateFilter,
sort,
updateSort,
clearFilter,
}}
>
{children}
</FilterContext.Provider>
)
}
export const useFilterContext = () => useContext(FilterContext)