-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCalendar.tsx
More file actions
103 lines (93 loc) · 2.67 KB
/
Calendar.tsx
File metadata and controls
103 lines (93 loc) · 2.67 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import type { Dayjs } from "dayjs";
import dayjs from "dayjs";
import isBetween from "dayjs/plugin/isBetween";
dayjs.extend(isBetween);
import { useMemo } from "react";
import {
CalendarCell,
CalendarDay,
CalendarHeader,
CalendarRow
} from "./DatePicker.style";
import { getCalenderRow, ICalendarCell } from "./utils";
export interface Props {
date: Dayjs | null;
secondDate: Dayjs | null;
month: Dayjs;
period: boolean;
onChange: (newDate: Dayjs | null) => void;
minDate: Dayjs | null | undefined;
maxDate: Dayjs | null | undefined;
}
export default function Calendar({
date,
secondDate,
month,
period,
onChange,
minDate,
maxDate
}: Props) {
const firstDay = date ? dayjs(date) : null;
const secondDay = secondDate ? dayjs(secondDate) : null;
const handleSelectDate = (value: Dayjs) => {
const isDateWithinMinMax =
(minDate
? value?.isSame(minDate, "day") || value?.isAfter(minDate, "day")
: true) &&
(maxDate
? value?.isSame(maxDate, "day") || value?.isBefore(maxDate, "day")
: true);
if (!isDateWithinMinMax) {
return onChange(null);
}
if (period && !isDateWithinMinMax) {
return onChange(null);
}
return onChange(value);
};
const rows = useMemo((): ICalendarCell[] => getCalenderRow(month), [month]);
return (
<>
<CalendarHeader>
{rows
.slice(0, 7)
.map(({ value }: ICalendarCell, headerIndex: number) => (
<CalendarCell key={`calendar_header_cell_${headerIndex}`}>
{value.format("dd")}
</CalendarCell>
))}
</CalendarHeader>
<CalendarRow>
{rows.map(({ text, value, current }: ICalendarCell, i: number) => {
const isBeforeMinDate = minDate
? value?.isBefore(minDate, "day")
: false;
const isAfterMaxDate = maxDate
? value?.isAfter(maxDate, "day")
: false;
const disabled: boolean = isBeforeMinDate || isAfterMaxDate;
return (
<CalendarDay
key={`calendar_row_day${text}-${i}`}
active={
secondDate
? value.isSame(firstDay, "day") ||
value.isSame(secondDay, "day")
: value.isSame(firstDay, "day")
}
between={
secondDate ? value.isBetween(firstDay, secondDay, "day") : false
}
disabled={disabled}
current={current}
onClick={() => handleSelectDate(value)}
>
<span>{text}</span>
</CalendarDay>
);
})}
</CalendarRow>
</>
);
}