UNPKG

1.69 kBJavaScriptView Raw
1import React from "react";
2import { addToRange, dateMatchModifiers } from "../utils/index.js";
3import { rangeIncludesDate } from "../utils/rangeIncludesDate.js";
4export function useRange(props, dateLib) {
5 const { disabled, excludeDisabled, selected: initiallySelected, required, onSelect } = props;
6 const [selected, setSelected] = React.useState(initiallySelected);
7 // Update the selected date if the `selected` prop changes.
8 React.useEffect(() => {
9 setSelected(initiallySelected);
10 }, [initiallySelected]);
11 const isSelected = (date) => selected && rangeIncludesDate(selected, date, false, dateLib);
12 const select = (triggerDate, modifiers, e) => {
13 const { min, max } = props;
14 const newRange = triggerDate
15 ? addToRange(triggerDate, selected, min, max, required, dateLib)
16 : undefined;
17 if (newRange?.from && newRange.to) {
18 let newDate = newRange.from;
19 while (dateLib.differenceInCalendarDays(newRange.to, newDate) > 0) {
20 newDate = dateLib.addDays(newDate, 1);
21 if (excludeDisabled &&
22 disabled &&
23 dateMatchModifiers(newDate, disabled, dateLib)) {
24 // if a disabled days is found, the range is reset
25 newRange.from = triggerDate;
26 newRange.to = undefined;
27 break;
28 }
29 }
30 }
31 setSelected(newRange);
32 onSelect?.(newRange, triggerDate, modifiers, e);
33 return newRange;
34 };
35 return {
36 selected,
37 select,
38 isSelected
39 };
40}
41//# sourceMappingURL=useRange.js.map
\No newline at end of file