1 | import React from "react";
|
2 |
|
3 | import type {
|
4 | DateLib,
|
5 | DayPickerProps,
|
6 | Modifiers,
|
7 | PropsSingle,
|
8 | SelectHandler,
|
9 | SelectedValue,
|
10 | Selection
|
11 | } from "../types/index.js";
|
12 |
|
13 | export type UseSingle<T extends DayPickerProps> = {
|
14 | select: SelectHandler<T>;
|
15 | isSelected: (date: Date) => boolean;
|
16 | selected: SelectedValue<T>;
|
17 | };
|
18 |
|
19 | export function useSingle<T extends DayPickerProps>(
|
20 | props: DayPickerProps,
|
21 | dateLib: DateLib
|
22 | ): Selection<T> {
|
23 | const {
|
24 | selected: initiallySelected,
|
25 | required,
|
26 | onSelect
|
27 | } = props as PropsSingle;
|
28 |
|
29 | const [selected, setSelected] = React.useState<Date | undefined>(
|
30 | initiallySelected
|
31 | );
|
32 |
|
33 | const { isSameDay } = dateLib;
|
34 |
|
35 |
|
36 | React.useEffect(() => {
|
37 | setSelected(initiallySelected);
|
38 | }, [initiallySelected]);
|
39 |
|
40 | const isSelected = (compareDate: Date) => {
|
41 | return selected ? isSameDay(selected, compareDate) : false;
|
42 | };
|
43 |
|
44 | const select = (
|
45 | triggerDate: Date,
|
46 | modifiers: Modifiers,
|
47 | e: React.MouseEvent | React.KeyboardEvent
|
48 | ) => {
|
49 | let newDate: Date | undefined = triggerDate;
|
50 | if (!required && selected && selected && isSameDay(triggerDate, selected)) {
|
51 |
|
52 | newDate = undefined;
|
53 | }
|
54 | setSelected(newDate);
|
55 | if (required) {
|
56 | onSelect?.(newDate as Date, triggerDate, modifiers, e);
|
57 | } else {
|
58 | onSelect?.(newDate, triggerDate, modifiers, e);
|
59 | }
|
60 | return newDate;
|
61 | };
|
62 |
|
63 | return {
|
64 | selected,
|
65 | select,
|
66 | isSelected
|
67 | } as Selection<T>;
|
68 | }
|