42 lines
1.0 KiB
TypeScript
42 lines
1.0 KiB
TypeScript
|
|
import { intervalToRange } from '@/utils/intervalToRange'
|
||
|
|
import { ComponentChild, createContext } from 'preact'
|
||
|
|
import { StateUpdater, useContext, useMemo, useState } from 'preact/hooks'
|
||
|
|
import { FilterValue } from '../components/Filters'
|
||
|
|
|
||
|
|
type DashboardContextType = {
|
||
|
|
filter: FilterValue
|
||
|
|
setFilter: StateUpdater<FilterValue>
|
||
|
|
}
|
||
|
|
|
||
|
|
const DashboardContext = createContext<DashboardContextType | null>(null)
|
||
|
|
|
||
|
|
export const DashboardContextProvider = ({
|
||
|
|
children,
|
||
|
|
}: {
|
||
|
|
children: ComponentChild
|
||
|
|
}) => {
|
||
|
|
const [filter, setFilter] = useState<FilterValue>(() => {
|
||
|
|
const range = intervalToRange('week', new Date(), new Date())
|
||
|
|
|
||
|
|
return { interval: 'week', customFrom: range[0], customTo: range[1] }
|
||
|
|
})
|
||
|
|
|
||
|
|
const value = useMemo(() => ({ filter, setFilter }), [filter])
|
||
|
|
|
||
|
|
return (
|
||
|
|
<DashboardContext.Provider value={value}>
|
||
|
|
{children}
|
||
|
|
</DashboardContext.Provider>
|
||
|
|
)
|
||
|
|
}
|
||
|
|
|
||
|
|
export const useDashboardContext = () => {
|
||
|
|
const ctx = useContext(DashboardContext)
|
||
|
|
|
||
|
|
if (!ctx) {
|
||
|
|
throw new Error('useDashboardContext used outside of DashboardContext')
|
||
|
|
}
|
||
|
|
|
||
|
|
return ctx
|
||
|
|
}
|