2020-09-19 19:35:05 +02:00
|
|
|
import { useDispatch, useSelector } from 'react-redux';
|
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';
|
2020-09-19 19:35:05 +02:00
|
|
|
import { getItem, setItem } from 'lib/web';
|
|
|
|
import { setDateRange } from '../redux/actions/websites';
|
|
|
|
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';
|
2020-09-01 00:02:32 +02:00
|
|
|
|
2020-09-19 19:35:05 +02:00
|
|
|
export default function useDateRange(websiteId, defaultDateRange = DEFAULT_DATE_RANGE) {
|
|
|
|
const dispatch = useDispatch();
|
2021-03-10 10:39:31 +01:00
|
|
|
const [locale] = useLocale();
|
2020-09-19 19:35:05 +02:00
|
|
|
const dateRange = useSelector(state => state.websites[websiteId]?.dateRange);
|
|
|
|
const forceUpdate = useForceUpdate();
|
|
|
|
|
|
|
|
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),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function saveDateRange(values) {
|
|
|
|
const { value } = values;
|
|
|
|
|
|
|
|
if (websiteId) {
|
|
|
|
dispatch(setDateRange(websiteId, values));
|
|
|
|
} else {
|
|
|
|
setItem(DATE_RANGE_CONFIG, value === 'custom' ? values : value);
|
|
|
|
forceUpdate();
|
|
|
|
}
|
2020-09-17 09:17:11 +02:00
|
|
|
}
|
|
|
|
|
2021-03-10 10:39:31 +01:00
|
|
|
return [dateRange || globalDateRange || getDateRange(defaultDateRange, locale), saveDateRange];
|
2020-09-01 00:02:32 +02:00
|
|
|
}
|