/
useField.ts
300 lines (264 loc) · 8.81 KB
/
useField.ts
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import * as React from 'react';
import useEnhancedEffect from '@mui/utils/useEnhancedEffect';
import useEventCallback from '@mui/utils/useEventCallback';
import { useTheme } from '@mui/material/styles';
import { useValidation } from '../useValidation';
import { useUtils } from '../useUtils';
import {
UseFieldParams,
UseFieldResponse,
UseFieldCommonForwardedProps,
UseFieldInternalProps,
AvailableAdjustKeyCode,
UseFieldTextField,
UseFieldForwardedProps,
UseFieldCommonAdditionalProps,
} from './useField.types';
import { adjustSectionValue, getSectionOrder } from './useField.utils';
import { useFieldState } from './useFieldState';
import { useFieldCharacterEditing } from './useFieldCharacterEditing';
import { PickerValidDate, FieldSection } from '../../../models';
import { useFieldV7TextField } from './useFieldV7TextField';
import { useFieldV6TextField } from './useFieldV6TextField';
export const useField = <
TValue,
TDate extends PickerValidDate,
TSection extends FieldSection,
TEnableAccessibleFieldDOMStructure extends boolean,
TForwardedProps extends UseFieldCommonForwardedProps &
UseFieldForwardedProps<TEnableAccessibleFieldDOMStructure>,
TInternalProps extends UseFieldInternalProps<
any,
any,
any,
TEnableAccessibleFieldDOMStructure,
any
> & {
minutesStep?: number;
},
>(
params: UseFieldParams<
TValue,
TDate,
TSection,
TEnableAccessibleFieldDOMStructure,
TForwardedProps,
TInternalProps
>,
): UseFieldResponse<TEnableAccessibleFieldDOMStructure, TForwardedProps> => {
const utils = useUtils<TDate>();
const {
internalProps,
internalProps: {
unstableFieldRef,
minutesStep,
enableAccessibleFieldDOMStructure = false,
disabled = false,
readOnly = false,
},
forwardedProps: { onKeyDown, error, clearable, onClear },
fieldValueManager,
valueManager,
validator,
} = params;
const theme = useTheme();
const isRTL = theme.direction === 'rtl';
const stateResponse = useFieldState(params);
const {
state,
activeSectionIndex,
parsedSelectedSections,
setSelectedSections,
clearValue,
clearActiveSection,
updateSectionValue,
setTempAndroidValueStr,
sectionsValueBoundaries,
localizedDigits,
timezone,
} = stateResponse;
const characterEditingResponse = useFieldCharacterEditing<TDate, TSection>({
sections: state.sections,
updateSectionValue,
sectionsValueBoundaries,
localizedDigits,
setTempAndroidValueStr,
timezone,
});
const { resetCharacterQuery } = characterEditingResponse;
const areAllSectionsEmpty = valueManager.areValuesEqual(
utils,
state.value,
valueManager.emptyValue,
);
const useFieldTextField = (
enableAccessibleFieldDOMStructure ? useFieldV7TextField : useFieldV6TextField
) as UseFieldTextField<TEnableAccessibleFieldDOMStructure>;
const sectionOrder = React.useMemo(
() => getSectionOrder(state.sections, isRTL && !enableAccessibleFieldDOMStructure),
[state.sections, isRTL, enableAccessibleFieldDOMStructure],
);
const { returnedValue, interactions } = useFieldTextField({
...params,
...stateResponse,
...characterEditingResponse,
areAllSectionsEmpty,
sectionOrder,
});
const handleContainerKeyDown = useEventCallback((event: React.KeyboardEvent<HTMLSpanElement>) => {
onKeyDown?.(event);
// eslint-disable-next-line default-case
switch (true) {
// Select all
case (event.ctrlKey || event.metaKey) &&
event.key.toLowerCase() === 'a' &&
!event.shiftKey &&
!event.altKey: {
// prevent default to make sure that the next line "select all" while updating
// the internal state at the same time.
event.preventDefault();
setSelectedSections('all');
break;
}
// Move selection to next section
case event.key === 'ArrowRight': {
event.preventDefault();
if (parsedSelectedSections == null) {
setSelectedSections(sectionOrder.startIndex);
} else if (parsedSelectedSections === 'all') {
setSelectedSections(sectionOrder.endIndex);
} else {
const nextSectionIndex = sectionOrder.neighbors[parsedSelectedSections].rightIndex;
if (nextSectionIndex !== null) {
setSelectedSections(nextSectionIndex);
}
}
break;
}
// Move selection to previous section
case event.key === 'ArrowLeft': {
event.preventDefault();
if (parsedSelectedSections == null) {
setSelectedSections(sectionOrder.endIndex);
} else if (parsedSelectedSections === 'all') {
setSelectedSections(sectionOrder.startIndex);
} else {
const nextSectionIndex = sectionOrder.neighbors[parsedSelectedSections].leftIndex;
if (nextSectionIndex !== null) {
setSelectedSections(nextSectionIndex);
}
}
break;
}
// Reset the value of the selected section
case event.key === 'Delete': {
event.preventDefault();
if (readOnly) {
break;
}
if (parsedSelectedSections == null || parsedSelectedSections === 'all') {
clearValue();
} else {
clearActiveSection();
}
resetCharacterQuery();
break;
}
// Increment / decrement the selected section value
case ['ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown'].includes(event.key): {
event.preventDefault();
if (readOnly || activeSectionIndex == null) {
break;
}
const activeSection = state.sections[activeSectionIndex];
const activeDateManager = fieldValueManager.getActiveDateManager(
utils,
state,
activeSection,
);
const newSectionValue = adjustSectionValue(
utils,
timezone,
activeSection,
event.key as AvailableAdjustKeyCode,
sectionsValueBoundaries,
localizedDigits,
activeDateManager.date,
{ minutesStep },
);
updateSectionValue({
activeSection,
newSectionValue,
shouldGoToNextSection: false,
});
break;
}
}
});
useEnhancedEffect(() => {
interactions.syncSelectionToDOM();
});
const validationError = useValidation(
{ ...internalProps, value: state.value, timezone },
validator,
valueManager.isSameError,
valueManager.defaultErrorState,
);
const inputError = React.useMemo(() => {
// only override when `error` is undefined.
// in case of multi input fields, the `error` value is provided externally and will always be defined.
if (error !== undefined) {
return error;
}
return valueManager.hasError(validationError);
}, [valueManager, validationError, error]);
React.useEffect(() => {
if (!inputError && activeSectionIndex == null) {
resetCharacterQuery();
}
}, [state.referenceValue, activeSectionIndex, inputError]); // eslint-disable-line react-hooks/exhaustive-deps
// If `tempValueStrAndroid` is still defined for some section when running `useEffect`,
// Then `onChange` has only been called once, which means the user pressed `Backspace` to reset the section.
// This causes a small flickering on Android,
// But we can't use `useEnhancedEffect` which is always called before the second `onChange` call and then would cause false positives.
React.useEffect(() => {
if (state.tempValueStrAndroid != null && activeSectionIndex != null) {
resetCharacterQuery();
clearActiveSection();
}
}, [state.sections]); // eslint-disable-line react-hooks/exhaustive-deps
React.useImperativeHandle(unstableFieldRef, () => ({
getSections: () => state.sections,
getActiveSectionIndex: interactions.getActiveSectionIndexFromDOM,
setSelectedSections: interactions.setSelectedSections,
focusField: interactions.focusField,
isFieldFocused: interactions.isFieldFocused,
}));
const handleClearValue = useEventCallback((event: React.MouseEvent, ...args) => {
event.preventDefault();
onClear?.(event, ...(args as []));
clearValue();
if (!interactions.isFieldFocused()) {
// setSelectedSections is called internally
interactions.focusField(0);
} else {
setSelectedSections(sectionOrder.startIndex);
}
});
const commonForwardedProps: Required<UseFieldCommonForwardedProps> = {
onKeyDown: handleContainerKeyDown,
onClear: handleClearValue,
error: inputError,
clearable: Boolean(clearable && !areAllSectionsEmpty && !readOnly && !disabled),
};
const commonAdditionalProps: UseFieldCommonAdditionalProps = {
disabled,
readOnly,
};
return {
...params.forwardedProps,
...commonForwardedProps,
...commonAdditionalProps,
...returnedValue,
};
};