-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathDatepickerContext.tsx
111 lines (104 loc) · 3.46 KB
/
DatepickerContext.tsx
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import React, { createContext, useState } from 'react';
import { Locale } from '../datelogic/types';
import { validateDate } from '../util/dateUtil';
import { getSimpleDateFromString } from '../datelogic/simpledate';
import { toNumber } from './toNumber';
interface DatepickerContextInterface {
day?: number | null;
month?: number | null;
year?: number | null;
setDay: (value: number[], focusNext?: () => void) => void;
setMonth: (value: number[], focusNext?: () => void) => void;
setYear: (value: number[]) => void;
locale: Locale;
calendarActiveDate?: string;
setCalendarActiveDate: (date: string) => void;
}
export const DatepickerContext = createContext<DatepickerContextInterface>({
day: null,
month: null,
year: null,
setDay: () => null,
setMonth: () => null,
setYear: () => null,
locale: 'nb',
calendarActiveDate: '',
setCalendarActiveDate: () => null,
});
interface Props {
locale: Locale;
value?: string;
children: React.ReactNode;
}
const MONTHS_PER_YEAR = 12;
const MAX_DAYS = 31;
export const DatepickerProvider: React.FC<Props> = ({
children,
value = '',
locale,
}) => {
const newDate = validateDate(value) ? getSimpleDateFromString(value) : '';
const [day, setDay] = useState<number | null>(
newDate ? newDate.date : null,
);
const [month, setMonth] = useState<number | null>(
newDate ? newDate.month + 1 : null,
);
const [year, setYear] = useState<number | null>(
newDate ? newDate.year : null,
);
const [calendarActiveDate, setCalendarActiveDate] = useState<string>(
newDate?.toString() ?? '',
);
return (
<DatepickerContext.Provider
value={{
day,
month,
year,
setDay: (newValue, focusNext = undefined) => {
const numbers = newValue.slice(-2);
const [first, second] = numbers;
const total = toNumber(numbers);
if (total > MAX_DAYS) {
focusNext?.();
} else if (first > 3) {
setDay(total);
focusNext?.();
} else {
setDay(total);
if (second !== undefined) {
focusNext?.();
}
}
},
setMonth: (newValue, focusNext = undefined) => {
const numbers = newValue.slice(-2);
const [first, second] = numbers;
const total = toNumber(numbers);
if (total > MONTHS_PER_YEAR) {
focusNext?.();
} else if (first > 1) {
setMonth(total);
focusNext?.();
} else {
setMonth(total);
if (second !== undefined) {
focusNext?.();
}
}
},
setYear: newValue => {
setYear(toNumber(newValue.slice(-4)));
},
calendarActiveDate,
setCalendarActiveDate: date => {
setCalendarActiveDate(date);
},
locale,
}}
>
{children}
</DatepickerContext.Provider>
);
};