/
SingleInputDateField.tsx
222 lines (212 loc) · 7.73 KB
/
SingleInputDateField.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import { useRef, useState } from 'react';
import type * as React from 'react';
import CustomDayPicker from './CustomDayPicker';
import classNames from 'classnames';
import cleanFieldProps from '../utilities/cleanFieldProps';
import describeField from '../utilities/describeField';
import { isMatch } from 'date-fns';
import mergeIds from '../utilities/mergeIds';
import useLabelMask from '../TextField/useLabelMask';
import useClickOutsideHandler from '../utilities/useClickOutsideHandler';
import usePressEscapeHandler from '../utilities/usePressEscapeHandler';
import useId from '../utilities/useId';
import { CalendarIcon } from '../Icons/CalendarIcon';
import { DATE_MASK } from '../TextField/useLabelMask';
import { Label } from '../Label';
import { TextInput } from '../TextField';
import { TextInputProps } from '../TextField/TextInput';
import { t } from '../i18n';
import { useLabelProps, UseLabelPropsProps } from '../Label/useLabelProps';
import { useHint, UseHintProps } from '../Hint/useHint';
import { useInlineError, UseInlineErrorProps } from '../InlineError/useInlineError';
interface BaseSingleInputDateFieldProps {
/**
* The `input` field's `name` attribute
*/
name: string;
/**
* Called anytime any date input is blurred
*/
onBlur?: (event: React.FocusEvent<HTMLInputElement>) => any;
/**
* Called anytime any date input is changed. This function is called with two arguments.
* The first argument should be used to update whatever state your application uses to
* supply back to this component's `value` prop in a _controlled component_ pattern.
*
* @param updatedValue - The input's new value
* @param formattedValue - The input's new value with date formatting applied, included
* for convenience. Do not use this value as the component's `value` prop. An appropriate
* use for this value would be to run date-validation checks against it.
*/
onChange: (updatedValue: string, formattedValue: string) => any;
/**
* A unique ID for this element. A unique ID will be generated if one isn't provided.
*/
id?: string;
/**
* Set to `true` to apply the "inverse" color scheme
*/
inversed?: boolean;
/**
* Sets the input's `value`. Use in combination with an `onChange` handler to implement
* a _controlled component_ pattern. This component expects the `value` to match
* whatever string the user types (i.e., the first argument provided to your `onChange`
* handler).
*/
value?: string;
// From DayPicker
// -------------------------
/**
* The initial month to show in the calendar picker. If not provided, defaults to the
* month of the currently selected date.
*/
defaultMonth?: Date;
/**
* Earliest day to start month navigation in the calendar picker.
* (This does not restrict dates entered manually.)
*/
fromDate?: Date;
/**
* Earliest month to start month navigation in the calendar picker.
* (This does not restrict dates entered manually.)
*/
fromMonth?: Date;
/**
* Earliest year to start month navigation in the calendar picker.
* (This does not restrict dates entered manually.)
*/
fromYear?: number;
/**
* Latest day to end month navigation in the calendar picker.
* (This does not restrict dates entered manually.)
*/
toDate?: Date;
/**
* Latest month to end month navigation in the calendar picker.
* (This does not restrict dates entered manually.)
*/
toMonth?: Date;
/**
* Latest year to end month navigation in the calendar picker.
* (This does not restrict dates entered manually.)
*/
toYear?: number;
}
export type SingleInputDateFieldProps = BaseSingleInputDateFieldProps &
Omit<TextInputProps, keyof BaseSingleInputDateFieldProps | 'type'> &
Omit<UseLabelPropsProps & UseHintProps & UseInlineErrorProps, 'id' | 'inversed'>;
/**
* For information about how and when to use this component, refer to the
* [Single Input Date Field](https://design.cms.gov/components/date-field/single-input-date-field/) and
* [Calendar Picker](https://design.cms.gov/components/date-field/date-picker/) documentation pages.
*/
const SingleInputDateField = (props: SingleInputDateFieldProps) => {
const {
className,
onChange,
defaultMonth,
fromDate,
fromMonth,
fromYear,
toDate,
toMonth,
toYear,
...remainingProps
} = props;
const withPicker =
(fromDate != null || fromMonth != null || Number.isInteger(fromYear)) &&
(toDate != null || toMonth != null || Number.isInteger(toYear));
const [pickerVisible, setPickerVisible] = useState(false);
const id = useId('date-field--', props.id);
// Set up change handlers
function handleInputChange(event) {
const updatedValue = event.currentTarget.value;
onChange(updatedValue, DATE_MASK(updatedValue, true));
}
function handlePickerChange(date: Date) {
const updatedValue = `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
onChange(DATE_MASK(updatedValue), DATE_MASK(updatedValue, true));
setPickerVisible(false);
inputRef.current?.focus();
}
// Collect all the props and elements for the input and its labels
const { errorId, topError, bottomError, invalid } = useInlineError({ ...props, id });
const { hintId, hintElement } = useHint({ ...props, id });
const labelProps = useLabelProps({ ...props, id });
const inputRef = useRef<HTMLInputElement>();
const { labelMask, inputProps } = useLabelMask(DATE_MASK, {
...cleanFieldProps(remainingProps),
id,
onChange: handleInputChange,
type: 'text',
inputRef: (el) => {
inputRef.current = el;
},
'aria-invalid': invalid,
'aria-describedby': describeField({ ...props, errorId, hintId }),
});
// Handle alternate ways of closing the day picker
const dayPickerRef = useRef();
const calendarButtonRef = useRef();
useClickOutsideHandler([dayPickerRef, calendarButtonRef], () => setPickerVisible(false));
usePressEscapeHandler(dayPickerRef, () => {
setPickerVisible(false);
inputRef.current?.focus();
});
// Validate the date string (value) and make date null if it's invalid. We don't want to pass
// a bizarre date to DayPicker like `new Date('01/02')`, which is interpreted as `Jan 02, 2001`
const dateString = DATE_MASK(props.value, true);
const validDateString = isMatch(dateString, 'MM/dd/yyyy');
const date = validDateString ? new Date(dateString) : null;
return (
<div
className={classNames(
'ds-c-single-input-date-field',
withPicker && 'ds-c-single-input-date-field--with-picker',
className
)}
>
<Label {...labelProps} fieldId={id} />
{hintElement}
{topError}
{labelMask}
<div className="ds-c-single-input-date-field__field-wrapper">
<TextInput {...inputProps} />
{withPicker && (
<button
className="ds-c-single-input-date-field__button"
onClick={() => setPickerVisible(!pickerVisible)}
type="button"
ref={calendarButtonRef}
aria-describedby={mergeIds(labelProps.id, hintId)}
>
<CalendarIcon
ariaHidden={false}
title={t(pickerVisible ? 'singleInputDateField.close' : 'singleInputDateField.open')}
id={`${id}__icon`}
/>
</button>
)}
</div>
{pickerVisible && (
<div ref={dayPickerRef} role="dialog">
<CustomDayPicker
selected={date}
onSelect={handlePickerChange}
defaultMonth={date ?? defaultMonth}
{...{
fromDate,
fromMonth,
fromYear,
toDate,
toMonth,
toYear,
}}
/>
</div>
)}
{bottomError}
</div>
);
};
export default SingleInputDateField;