UNPKG

1.64 kBJavaScriptView Raw
1import React from "react";
2export function useMulti(props, dateLib) {
3 const { selected: initiallySelected, required, onSelect, mode } = props;
4 const [selected, setSelected] = React.useState(initiallySelected);
5 const { isSameDay } = dateLib;
6 // Update the selected date if the selected value from props changes.
7 React.useEffect(() => {
8 setSelected(initiallySelected);
9 }, [mode, initiallySelected]);
10 const isSelected = (date) => {
11 return selected?.some((d) => isSameDay(d, date)) ?? false;
12 };
13 const { min, max } = props;
14 const select = (triggerDate, modifiers, e) => {
15 let newDates = [...(selected ?? [])];
16 if (isSelected(triggerDate)) {
17 if (selected?.length === min) {
18 // Min value reached, do nothing
19 return;
20 }
21 if (required && selected?.length === 1) {
22 // Required value already selected do nothing
23 return;
24 }
25 newDates = selected?.filter((d) => !isSameDay(d, triggerDate));
26 }
27 else {
28 if (selected?.length === max) {
29 // Max value reached, reset the selection to date
30 newDates = [triggerDate];
31 }
32 else {
33 // Add the date to the selection
34 newDates = [...newDates, triggerDate];
35 }
36 }
37 onSelect?.(newDates, triggerDate, modifiers, e);
38 setSelected(newDates);
39 return newDates;
40 };
41 return {
42 selected,
43 select,
44 isSelected
45 };
46}
47//# sourceMappingURL=useMulti.js.map
\No newline at end of file