graphicek/client/src/pages/dashboard/contexts/DashboardContext.tsx

51 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-08-24 09:45:54 +02:00
import { useViewportSize } from '@/utils/hooks/useViewportSize'
2022-08-24 08:59:18 +02:00
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>
2022-08-24 09:45:54 +02:00
verticalMode: boolean
2022-08-24 08:59:18 +02:00
}
const DashboardContext = createContext<DashboardContextType | null>(null)
export const DashboardContextProvider = ({
children,
}: {
children: ComponentChild
}) => {
2022-08-24 09:45:54 +02:00
const viewport = useViewportSize()
2022-08-24 08:59:18 +02:00
const [filter, setFilter] = useState<FilterValue>(() => {
const range = intervalToRange('week', new Date(), new Date())
return { interval: 'week', customFrom: range[0], customTo: range[1] }
})
2022-08-24 09:45:54 +02:00
const verticalMode = viewport.width < 800
const value = useMemo(
() => ({ filter, setFilter, verticalMode }),
[filter, verticalMode]
)
2022-08-24 08:59:18 +02:00
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
}