umami/components/forms/DatePickerForm.js

84 lines
2.6 KiB
JavaScript
Raw Normal View History

2020-09-13 10:26:54 +02:00
import React, { useState } from 'react';
import { FormattedMessage } from 'react-intl';
2020-09-17 01:28:54 +02:00
import { isAfter, isBefore, isSameDay } from 'date-fns';
2020-09-13 10:26:54 +02:00
import Calendar from 'components/common/Calendar';
import Button from 'components/common/Button';
import { FormButtons } from 'components/layout/FormLayout';
import { getDateRangeValues } from 'lib/date';
import styles from './DatePickerForm.module.css';
2020-09-20 10:33:39 +02:00
import ButtonGroup from 'components/common/ButtonGroup';
2020-09-17 01:28:54 +02:00
const FILTER_DAY = 0;
const FILTER_RANGE = 1;
2020-09-13 10:26:54 +02:00
export default function DatePickerForm({
startDate: defaultStartDate,
endDate: defaultEndDate,
minDate,
maxDate,
onChange,
onClose,
}) {
2020-09-17 01:28:54 +02:00
const [selected, setSelected] = useState(
isSameDay(defaultStartDate, defaultEndDate) ? FILTER_DAY : FILTER_RANGE,
);
const [date, setDate] = useState(defaultStartDate);
2020-09-13 10:26:54 +02:00
const [startDate, setStartDate] = useState(defaultStartDate);
const [endDate, setEndDate] = useState(defaultEndDate);
2020-09-17 01:28:54 +02:00
const disabled =
selected === FILTER_DAY
? isAfter(minDate, date) && isBefore(maxDate, date)
: isAfter(startDate, endDate);
const buttons = [
{
label: <FormattedMessage id="button.single-day" defaultMessage="Single day" />,
value: FILTER_DAY,
},
{
label: <FormattedMessage id="button.date-range" defaultMessage="Date range" />,
value: FILTER_RANGE,
},
];
2020-09-13 10:26:54 +02:00
function handleSave() {
2020-09-17 01:28:54 +02:00
if (selected === FILTER_DAY) {
onChange({ ...getDateRangeValues(date, date), value: 'custom' });
} else {
onChange({ ...getDateRangeValues(startDate, endDate), value: 'custom' });
}
2020-09-13 10:26:54 +02:00
}
return (
<div className={styles.container}>
2020-09-17 01:28:54 +02:00
<div className={styles.filter}>
<ButtonGroup size="small" items={buttons} selectedItem={selected} onClick={setSelected} />
</div>
2020-09-13 10:26:54 +02:00
<div className={styles.calendars}>
2020-09-17 01:28:54 +02:00
{selected === FILTER_DAY ? (
<Calendar date={date} minDate={minDate} maxDate={maxDate} onChange={setDate} />
) : (
<>
<Calendar
date={startDate}
minDate={minDate}
maxDate={endDate}
onChange={setStartDate}
/>
<Calendar date={endDate} minDate={startDate} maxDate={maxDate} onChange={setEndDate} />
</>
)}
2020-09-13 10:26:54 +02:00
</div>
<FormButtons>
2020-09-17 01:28:54 +02:00
<Button variant="action" onClick={handleSave} disabled={disabled}>
2020-09-13 10:26:54 +02:00
<FormattedMessage id="button.save" defaultMessage="Save" />
</Button>
<Button onClick={onClose}>
<FormattedMessage id="button.cancel" defaultMessage="Cancel" />
</Button>
</FormButtons>
</div>
);
}