shlink-web-client/shlink-web-component/utils/dates/DateRangeSelector.tsx

68 lines
2.5 KiB
TypeScript
Raw Normal View History

import { useState } from 'react';
import { DropdownItem } from 'reactstrap';
import { DropdownBtn } from '../../../src/utils/DropdownBtn';
import { useEffectExceptFirstTime } from '../helpers/hooks';
import { DateIntervalDropdownItems } from './DateIntervalDropdownItems';
import { DateRangeRow } from './DateRangeRow';
2023-02-18 12:40:37 +03:00
import type {
DateInterval,
DateRange } from './helpers/dateIntervals';
2023-02-18 12:40:37 +03:00
import {
2023-02-18 13:11:01 +03:00
ALL,
dateRangeIsEmpty,
intervalToDateRange,
rangeIsInterval,
2023-02-18 13:11:01 +03:00
rangeOrIntervalToString,
} from './helpers/dateIntervals';
2020-12-15 01:15:06 +03:00
export interface DateRangeSelectorProps {
initialDateRange?: DateInterval | DateRange;
disabled?: boolean;
onDatesChange: (dateRange: DateRange) => void;
defaultText: string;
updatable?: boolean;
}
export const DateRangeSelector = (
{ onDatesChange, initialDateRange, defaultText, disabled, updatable = false }: DateRangeSelectorProps,
) => {
const initialIntervalIsRange = rangeIsInterval(initialDateRange);
const [activeInterval, setActiveInterval] = useState<DateInterval | undefined>(
initialIntervalIsRange ? initialDateRange : undefined,
);
2022-03-26 14:17:42 +03:00
const [activeDateRange, setActiveDateRange] = useState(initialIntervalIsRange ? undefined : initialDateRange);
const updateDateRange = (dateRange: DateRange) => {
setActiveInterval(dateRangeIsEmpty(dateRange) ? ALL : undefined);
setActiveDateRange(dateRange);
onDatesChange(dateRange);
};
const updateInterval = (dateInterval: DateInterval) => {
setActiveInterval(dateInterval);
setActiveDateRange(undefined);
onDatesChange(intervalToDateRange(dateInterval));
};
updatable && useEffectExceptFirstTime(() => {
const isDateInterval = rangeIsInterval(initialDateRange);
isDateInterval && updateInterval(initialDateRange);
initialDateRange && !isDateInterval && updateDateRange(initialDateRange);
2022-03-26 14:17:42 +03:00
}, [initialDateRange]);
return (
<DropdownBtn disabled={disabled} text={rangeOrIntervalToString(activeInterval ?? activeDateRange) ?? defaultText}>
<DateIntervalDropdownItems allText={defaultText} active={activeInterval} onChange={updateInterval} />
<DropdownItem divider />
<DropdownItem header>Custom:</DropdownItem>
<DropdownItem text>
<DateRangeRow
{...activeDateRange}
onStartDateChange={(startDate) => updateDateRange({ ...activeDateRange, startDate })}
onEndDateChange={(endDate) => updateDateRange({ ...activeDateRange, endDate })}
/>
</DropdownItem>
</DropdownBtn>
);
};