UNPKG

2.62 kBJavaScriptView Raw
1"use strict";
2var __assign = (this && this.__assign) || function () {
3 __assign = Object.assign || function(t) {
4 for (var s, i = 1, n = arguments.length; i < n; i++) {
5 s = arguments[i];
6 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 t[p] = s[p];
8 }
9 return t;
10 };
11 return __assign.apply(this, arguments);
12};
13Object.defineProperty(exports, "__esModule", { value: true });
14var useUtils_1 = require("./useUtils");
15var react_1 = require("react");
16var text_field_helper_1 = require("../../_helpers/text-field-helper");
17var usePickerState_1 = require("./usePickerState");
18function parseInputString(value, utils, format) {
19 try {
20 return utils.parse(value, format);
21 }
22 catch (_a) {
23 return null;
24 }
25}
26function useKeyboardPickerState(props, options) {
27 var _a = props.format, format = _a === void 0 ? options.getDefaultFormat() : _a, inputValue = props.inputValue, onChange = props.onChange, value = props.value;
28 var utils = useUtils_1.useUtils();
29 var displayDate = text_field_helper_1.getDisplayDate(value, format, utils, value === null, props);
30 var _b = react_1.useState(displayDate), innerInputValue = _b[0], setInnerInputValue = _b[1];
31 var dateValue = inputValue ? parseInputString(inputValue, utils, format) : value;
32 react_1.useEffect(function () {
33 if (value === null || utils.isValid(value)) {
34 setInnerInputValue(displayDate);
35 }
36 }, [displayDate, setInnerInputValue, utils, value]);
37 var handleKeyboardChange = react_1.useCallback(function (date) {
38 onChange(date, date === null ? null : utils.format(date, format));
39 }, [format, onChange, utils]);
40 var _c = usePickerState_1.usePickerState(__assign(__assign({}, props), { value: dateValue, onChange: handleKeyboardChange }), options), innerInputProps = _c.inputProps, wrapperProps = _c.wrapperProps, pickerProps = _c.pickerProps;
41 var inputProps = react_1.useMemo(function () { return (__assign(__assign({}, innerInputProps), { format: wrapperProps.format, inputValue: inputValue || innerInputValue, onChange: function (value) {
42 setInnerInputValue(value || '');
43 var date = value === null ? null : utils.parse(value, wrapperProps.format);
44 onChange(date, value);
45 } })); }, [innerInputProps, innerInputValue, inputValue, onChange, utils, wrapperProps.format]);
46 return {
47 inputProps: inputProps,
48 wrapperProps: wrapperProps,
49 pickerProps: pickerProps,
50 };
51}
52exports.useKeyboardPickerState = useKeyboardPickerState;