-
Notifications
You must be signed in to change notification settings - Fork 54
/
useDay.ts
58 lines (53 loc) · 1.63 KB
/
useDay.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
import React, {useCallback} from 'react'
import addDays from 'date-fns/addDays'
interface UseDayProps {
date: Date
focusedDate: Date | null
isDateFocused(date: Date): boolean
isDateSelected(date: Date): boolean
isDateHovered(date: Date): boolean
isDateBlocked(date: Date): boolean
isFirstOrLastSelectedDate(date: Date): boolean
onDateFocus(date: Date): void
onDateSelect(date: Date): void
onDateHover(date: Date): void
// Not used anymore
dayRef?: React.RefObject<HTMLButtonElement>
}
function useDay({
date,
focusedDate,
isDateSelected,
isDateFocused,
isFirstOrLastSelectedDate,
isDateHovered,
isDateBlocked,
onDateSelect,
onDateFocus,
onDateHover,
}: UseDayProps) {
const onClick = useCallback(() => onDateSelect(date), [date, onDateSelect])
const onMouseEnter = useCallback(() => onDateHover(date), [date, onDateHover])
const disabled = isDateBlocked(date) && !isDateHovered(date)
return {
tabIndex: focusedDate === null || isDateFocused(date) ? 0 : -1,
isSelected: isDateSelected(date),
isSelectedStartOrEnd: isFirstOrLastSelectedDate(date),
isWithinHoverRange: isDateHovered(date),
disabledDate: disabled,
onKeyDown: (e: React.KeyboardEvent<HTMLButtonElement>) => {
if (e.key === 'ArrowRight') {
onDateFocus(addDays(date, 1))
} else if (e.key === 'ArrowLeft') {
onDateFocus(addDays(date, -1))
} else if (e.key === 'ArrowUp') {
onDateFocus(addDays(date, -7))
} else if (e.key === 'ArrowDown') {
onDateFocus(addDays(date, 7))
}
},
onClick: disabled ? () => {} : onClick,
onMouseEnter,
}
}
export default useDay