aboutsummaryrefslogtreecommitdiff
path: root/src/components/metrics/DatePickerForm.tsx
blob: 59d17093784934af976f8952d43e070ae33a8912 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { Button, Calendar, Column, Row, ToggleGroup, ToggleGroupItem } from '@umami/react-zen';
import { endOfDay, isAfter, isBefore, isSameDay, startOfDay } from 'date-fns';
import { useState } from 'react';
import { useMessages } from '@/components/hooks';

const FILTER_DAY = 'filter-day';
const FILTER_RANGE = 'filter-range';

export function DatePickerForm({
  startDate: defaultStartDate,
  endDate: defaultEndDate,
  minDate,
  maxDate,
  onChange,
  onClose,
}) {
  const [selected, setSelected] = useState<any>([
    isSameDay(defaultStartDate, defaultEndDate) ? FILTER_DAY : FILTER_RANGE,
  ]);
  const [date, setDate] = useState(defaultStartDate || new Date());
  const [startDate, setStartDate] = useState(defaultStartDate || new Date());
  const [endDate, setEndDate] = useState(defaultEndDate || new Date());
  const { formatMessage, labels } = useMessages();

  const disabled = selected.includes(FILTER_DAY)
    ? isAfter(minDate, date) && isBefore(maxDate, date)
    : isAfter(startDate, endDate);

  const handleSave = () => {
    if (selected.includes(FILTER_DAY)) {
      onChange(`range:${startOfDay(date).getTime()}:${endOfDay(date).getTime()}`);
    } else {
      onChange(`range:${startOfDay(startDate).getTime()}:${endOfDay(endDate).getTime()}`);
    }
  };

  return (
    <Column gap>
      <Row justifyContent="center">
        <ToggleGroup disallowEmptySelection value={selected} onChange={setSelected}>
          <ToggleGroupItem id={FILTER_DAY}>{formatMessage(labels.singleDay)}</ToggleGroupItem>
          <ToggleGroupItem id={FILTER_RANGE}>{formatMessage(labels.dateRange)}</ToggleGroupItem>
        </ToggleGroup>
      </Row>
      <Column>
        {selected.includes(FILTER_DAY) && (
          <Calendar value={date} minValue={minDate} maxValue={maxDate} onChange={setDate} />
        )}
        {selected.includes(FILTER_RANGE) && (
          <Row gap wrap="wrap" style={{ margin: '0 auto' }}>
            <Calendar
              value={startDate}
              minValue={minDate}
              maxValue={endDate}
              onChange={setStartDate}
            />
            <Calendar
              value={endDate}
              minValue={startDate}
              maxValue={maxDate}
              onChange={setEndDate}
            />
          </Row>
        )}
      </Column>
      <Row justifyContent="end" gap>
        <Button onPress={onClose}>{formatMessage(labels.cancel)}</Button>
        <Button variant="primary" onPress={handleSave} isDisabled={disabled}>
          {formatMessage(labels.apply)}
        </Button>
      </Row>
    </Column>
  );
}