2022-03-02 08:03:50 +01:00
|
|
|
import { useCallback, useMemo } from 'react';
|
2020-09-17 09:17:11 +02:00
|
|
|
import { parseISO } from 'date-fns';
|
2020-09-01 00:02:32 +02:00
|
|
|
import { getDateRange } from 'lib/date';
|
2022-08-29 05:20:54 +02:00
|
|
|
import { getItem, setItem } from 'next-basics';
|
2020-09-19 19:35:05 +02:00
|
|
|
import { DATE_RANGE_CONFIG, DEFAULT_DATE_RANGE } from 'lib/constants';
|
|
|
|
import useForceUpdate from './useForceUpdate';
|
2021-03-10 10:39:31 +01:00
|
|
|
import useLocale from './useLocale';
|
2022-02-23 07:47:59 +01:00
|
|
|
import useStore, { setDateRange } from 'store/websites';
|
2020-09-01 00:02:32 +02:00
|
|
|
|
2022-03-02 07:02:31 +01:00
|
|
|
export default function useDateRange(websiteId) {
|
2021-06-30 03:41:34 +02:00
|
|
|
const { locale } = useLocale();
|
2022-03-02 08:03:50 +01:00
|
|
|
const forceUpdate = useForceUpdate();
|
2022-02-23 07:47:59 +01:00
|
|
|
const selector = useCallback(state => state?.[websiteId]?.dateRange, [websiteId]);
|
2022-03-02 07:02:31 +01:00
|
|
|
const websiteDateRange = useStore(selector);
|
2022-03-02 08:03:50 +01:00
|
|
|
const defaultDateRange = useMemo(() => getDateRange(DEFAULT_DATE_RANGE, locale), [locale]);
|
2020-09-19 19:35:05 +02:00
|
|
|
|
|
|
|
const globalDefault = getItem(DATE_RANGE_CONFIG);
|
2020-09-19 00:40:42 +02:00
|
|
|
let globalDateRange;
|
2020-09-17 09:17:11 +02:00
|
|
|
|
2020-09-19 19:35:05 +02:00
|
|
|
if (globalDefault) {
|
|
|
|
if (typeof globalDefault === 'string') {
|
2021-03-10 10:39:31 +01:00
|
|
|
globalDateRange = getDateRange(globalDefault, locale);
|
2020-09-19 19:35:05 +02:00
|
|
|
} else if (typeof globalDefault === 'object') {
|
|
|
|
globalDateRange = {
|
|
|
|
...globalDefault,
|
|
|
|
startDate: parseISO(globalDefault.startDate),
|
|
|
|
endDate: parseISO(globalDefault.endDate),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-23 07:47:59 +01:00
|
|
|
function saveDateRange(dateRange) {
|
2020-09-19 19:35:05 +02:00
|
|
|
if (websiteId) {
|
2022-02-23 07:47:59 +01:00
|
|
|
setDateRange(websiteId, dateRange);
|
2020-09-19 19:35:05 +02:00
|
|
|
} else {
|
2022-03-02 07:02:31 +01:00
|
|
|
setItem(DATE_RANGE_CONFIG, dateRange);
|
2020-09-19 19:35:05 +02:00
|
|
|
forceUpdate();
|
|
|
|
}
|
2020-09-17 09:17:11 +02:00
|
|
|
}
|
|
|
|
|
2022-03-02 07:02:31 +01:00
|
|
|
return [websiteDateRange || globalDateRange || defaultDateRange, saveDateRange];
|
2020-09-01 00:02:32 +02:00
|
|
|
}
|