51 lines
1.2 KiB
TypeScript
51 lines
1.2 KiB
TypeScript
import { useViewportSize } from '@/utils/hooks/useViewportSize'
|
|
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>
|
|
verticalMode: boolean
|
|
}
|
|
|
|
const DashboardContext = createContext<DashboardContextType | null>(null)
|
|
|
|
export const DashboardContextProvider = ({
|
|
children,
|
|
}: {
|
|
children: ComponentChild
|
|
}) => {
|
|
const viewport = useViewportSize()
|
|
|
|
const [filter, setFilter] = useState<FilterValue>(() => {
|
|
const range = intervalToRange('week', new Date(), new Date())
|
|
|
|
return { interval: 'week', customFrom: range[0], customTo: range[1] }
|
|
})
|
|
|
|
const verticalMode = viewport.width < 800
|
|
|
|
const value = useMemo(
|
|
() => ({ filter, setFilter, verticalMode }),
|
|
[filter, verticalMode]
|
|
)
|
|
|
|
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
|
|
}
|