-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
use-days.ts
95 lines (89 loc) · 2.57 KB
/
use-days.ts
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
import { useCallback, useMemo } from 'react';
import { setFocus, setRangeEnd as setRangeEndAction } from './state-reducer';
import type {
DPDay,
DPPropsGetterConfig,
DPUseDays,
DPUseDaysPropGetters,
} from './types';
import { callAll, skipFirst } from './utils/call-all';
import { isRange } from './utils/config';
import { createPropGetter } from './utils/create-prop-getter';
import { formatDate, getCleanDate } from './utils/date';
import { getMultipleDates } from './utils/get-multiple-dates';
import { includeDate, isSame } from './utils/predicates';
export const useDays: DPUseDays = ({ selectedDates, config: { locale } }) =>
useMemo(
() => ({
selectedDates,
formattedDates: selectedDates.map((d: Date) => formatDate(d, locale)),
}),
[selectedDates, locale],
);
export const useDaysPropGetters: DPUseDaysPropGetters = ({
config,
selectedDates,
dispatch,
}) => {
const {
onDatesChange,
dates: { mode, toggle, selectSameDate },
} = config;
const dayButton = useCallback(
(
{ $date, selected, disabled, active }: DPDay,
{ onClick, disabled: disabledProps, ...rest }: DPPropsGetterConfig = {},
) =>
createPropGetter(
disabled || !!disabledProps,
(evt) => {
if (selected && !toggle) {
selectedDates.forEach((d) => {
if (isSame(getCleanDate(d), $date)) setFocus(dispatch, d);
});
// Handle case when user could select same date in range mode
if (!isRange(mode) || !selectSameDate) return;
}
if (isRange(mode) && selectedDates.length === 1) {
setRangeEndAction(dispatch, null);
}
callAll(
onClick,
skipFirst((d: Date) => {
const nextSelectedDates = getMultipleDates(
selectedDates,
d,
config.dates,
);
setFocus(
dispatch,
includeDate(nextSelectedDates, d) ? d : undefined,
);
onDatesChange(nextSelectedDates);
}),
)(evt, $date);
},
{
...rest,
...(isRange(mode) &&
selectedDates.length === 1 && {
onMouseEnter() {
setRangeEndAction(dispatch, $date);
},
}),
tabIndex: active ? 0 : -1,
},
selected,
),
[
mode,
toggle,
config.dates,
onDatesChange,
selectedDates,
dispatch,
selectSameDate,
],
);
return { dayButton };
};