rsuite
Version:
A suite of react components
286 lines (280 loc) • 10.5 kB
JavaScript
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import React, { useState, useRef, useMemo } from 'react';
import Input from "../Input/index.js";
import { isValid } from "../internals/utils/date/index.js";
import { useStyles, useCustom, useControlled, useEventCallback } from "../internals/hooks/index.js";
import { mergeRefs } from "../internals/utils/index.js";
import { validateDateTime, useDateInputState, useInputSelection, useKeyboardInputEvent, useIsFocused, useSelectedState, useFieldCursor } from "../DateInput/index.js";
import { getInputSelectedState, DateType, getDateType, isSwitchDateType } from "./utils.js";
/**
* The DateRangeInput component lets users select a date with the keyboard.
* @version 5.59.0
* @see https://rsuitejs.com/components/date-range-input/
*/
const DateRangeInput = /*#__PURE__*/React.forwardRef((props, ref) => {
const {
propsWithDefaults,
parseDate,
getLocale
} = useCustom('Calendar', props);
const {
shortDateFormat,
dateLocale
} = getLocale('DateTimeFormats');
const {
className,
classPrefix = 'date-range-input',
character = ' ~ ',
format: formatStr = shortDateFormat,
value: valueProp,
defaultValue = [],
placeholder,
onChange,
onKeyDown,
onBlur,
onFocus,
onPaste,
...rest
} = propsWithDefaults;
const {
withPrefix,
merge
} = useStyles(classPrefix);
const classes = merge(className, withPrefix());
const inputRef = useRef(null);
const {
selectedState,
setSelectedState
} = useSelectedState();
const rangeFormatStr = `${formatStr}${character}${formatStr}`;
const [value, setValue, isControlled] = useControlled(valueProp, defaultValue);
const [dateType, setDateType] = useState(DateType.Start);
const dateInputOptions = {
formatStr,
locale: dateLocale,
isControlledDate: isControlled
};
const startDateState = useDateInputState({
...dateInputOptions,
date: (value === null || value === void 0 ? void 0 : value[0]) || null
});
const endDateState = useDateInputState({
...dateInputOptions,
date: (value === null || value === void 0 ? void 0 : value[1]) || null
});
const {
isMoveCursor,
isResetValue,
increment,
reset
} = useFieldCursor(formatStr, valueProp);
const getActiveState = (type = dateType) => {
return type === DateType.Start ? startDateState : endDateState;
};
const [focused, focusEventProps] = useIsFocused({
onBlur,
onFocus
});
const renderedValue = useMemo(() => {
const dateString = startDateState.toDateString() + character + endDateState.toDateString();
if (!startDateState.isEmptyValue() || !endDateState.isEmptyValue()) {
return dateString;
}
return !focused ? '' : dateString;
}, [character, endDateState, focused, startDateState]);
const keyPressOptions = {
formatStr,
rangeFormatStr,
localize: dateLocale.localize,
selectedMonth: getActiveState().dateField.month,
dateString: renderedValue,
dateType,
character
};
const setSelectionRange = useInputSelection(inputRef);
const handleChange = useEventCallback((date, event) => {
const nextValue = dateType === DateType.Start ? [date, value === null || value === void 0 ? void 0 : value[1]] : [value === null || value === void 0 ? void 0 : value[0], date];
onChange === null || onChange === void 0 || onChange(nextValue, event);
setValue(nextValue);
});
const handleClear = useEventCallback(event => {
startDateState.setNewDate(null);
endDateState.setNewDate(null);
setSelectionRange(0, 0);
reset();
setValue(null);
onChange === null || onChange === void 0 || onChange(null, event);
});
const onSegmentChange = useEventCallback((event, nextDirection) => {
const input = event.target;
const key = event.key;
const direction = nextDirection || (key === 'ArrowRight' ? 'right' : 'left');
if (input.selectionEnd === null || input.selectionStart === null) {
return;
}
const cursorIndex = direction === 'right' ? input.selectionEnd : input.selectionStart;
let nextDateType = dateType;
if (isSwitchDateType(renderedValue, character, cursorIndex, direction)) {
nextDateType = dateType === DateType.Start ? DateType.End : DateType.Start;
setDateType(nextDateType);
}
const state = getInputSelectedState({
...keyPressOptions,
dateType: nextDateType,
selectedMonth: getActiveState(nextDateType).dateField.month,
input,
direction
});
setSelectedState(state);
setSelectionRange(state.selectionStart, state.selectionEnd);
// If the selected field changes, reset the input state
if (selectedState.selectedPattern !== state.selectedPattern) {
reset();
}
});
const onSegmentValueChange = useEventCallback(event => {
const input = event.target;
const key = event.key;
const offset = key === 'ArrowUp' ? 1 : -1;
const state = getInputSelectedState({
...keyPressOptions,
input,
valueOffset: offset
});
setSelectedState(state);
getActiveState().setDateOffset(state.selectedPattern, offset, date => handleChange(date, event));
setSelectionRange(state.selectionStart, state.selectionEnd);
});
const onSegmentValueChangeWithNumericKeys = useEventCallback(event => {
const input = event.target;
const key = event.key;
const pattern = selectedState.selectedPattern;
const isFunctionKey = key.startsWith('F') && !isNaN(Number(key.slice(1)));
if (isFunctionKey) {
return;
}
if (!pattern) {
return;
}
const field = getActiveState().getDateField(pattern);
const value = parseInt(key, 10);
const padValue = parseInt(`${field.value || ''}${key}`, 10);
let newValue = value;
// Check if the value entered by the user is a valid date
if (validateDateTime(field.name, padValue) && !isResetValue()) {
newValue = padValue;
}
getActiveState().setDateField(pattern, newValue, date => handleChange(date, event));
// The currently selected month will be retained as a parameter of getInputSelectedState,
// but if the user enters a month, the month value will be replaced with the value entered by the user.
const selectedMonth = pattern === 'M' ? newValue : getActiveState().dateField.month;
const nextState = getInputSelectedState({
...keyPressOptions,
input,
selectedMonth
});
setSelectedState(nextState);
setSelectionRange(nextState.selectionStart, nextState.selectionEnd);
increment();
// If the field is full value, move the cursor to the next field
if (isMoveCursor(newValue, pattern) && input.selectionEnd !== input.value.length) {
onSegmentChange(event, 'right');
}
});
const onSegmentValueRemove = useEventCallback(event => {
const input = event.target;
const value = input.value;
if (input.selectionStart === 0 && value && input.selectionEnd === value.length) {
handleClear(event);
} else if (selectedState.selectedPattern) {
const nextState = getInputSelectedState({
...keyPressOptions,
input,
valueOffset: null
});
setSelectedState(nextState);
setSelectionRange(nextState.selectionStart, nextState.selectionEnd);
getActiveState().setDateField(selectedState.selectedPattern, null, date => handleChange(date, event));
reset();
}
});
const onAmPmToggle = useEventCallback(event => {
const input = event.target;
const key = event.key.toLowerCase();
// Only handle 'a' or 'p' keys when the selected pattern is 'a' (AM/PM)
if (selectedState.selectedPattern === 'a' && (key === 'a' || key === 'p')) {
const currentHour = getActiveState().dateField.hour || 0;
const isAM = currentHour < 12;
const isPM = currentHour >= 12;
// Toggle AM/PM based on the key pressed
// 'a' key -> set to AM, 'p' key -> set to PM
if (key === 'a' && isPM || key === 'p' && isAM) {
const state = getInputSelectedState({
...keyPressOptions,
input
});
setSelectedState(state);
getActiveState().setDateOffset('a', 1, date => handleChange(date, event));
setSelectionRange(state.selectionStart, state.selectionEnd);
}
}
});
const handleClick = useEventCallback(event => {
const input = event.target;
if (input.selectionStart === null) {
return;
}
const cursorIndex = input.selectionStart === renderedValue.length ? 0 : input.selectionStart;
const dateType = getDateType(renderedValue || rangeFormatStr, character, cursorIndex);
const state = getInputSelectedState({
...keyPressOptions,
dateType,
selectedMonth: getActiveState(dateType).dateField.month,
input
});
setDateType(dateType);
setSelectedState(state);
setSelectionRange(state.selectionStart, state.selectionEnd);
if (selectedState.selectedPattern !== state.selectedPattern) {
reset();
}
});
const handlePaste = useEventCallback(event => {
var _event$clipboardData;
event.preventDefault();
const pasteText = (_event$clipboardData = event.clipboardData) === null || _event$clipboardData === void 0 ? void 0 : _event$clipboardData.getData('text');
const [start, end] = pasteText.split(character).map(date => parseDate(date, formatStr));
if (isValid(start) && isValid(end)) {
const nextValue = [start, end];
onChange === null || onChange === void 0 || onChange(nextValue, event);
setValue(nextValue);
startDateState.setNewDate(start);
endDateState.setNewDate(end);
}
onPaste === null || onPaste === void 0 || onPaste(event);
});
const onKeyboardInput = useKeyboardInputEvent({
onSegmentChange,
onSegmentValueChange,
onSegmentValueChangeWithNumericKeys,
onSegmentValueRemove,
onAmPmToggle,
onKeyDown
});
return /*#__PURE__*/React.createElement(Input, _extends({
inputMode: focused ? 'numeric' : 'text',
autoComplete: "off",
autoCorrect: "off",
spellCheck: false,
className: classes,
ref: mergeRefs(inputRef, ref),
onKeyDown: onKeyboardInput,
onClick: handleClick,
onPaste: handlePaste,
value: renderedValue,
placeholder: placeholder || rangeFormatStr
}, focusEventProps, rest));
});
DateRangeInput.displayName = 'DateRangeInput';
export default DateRangeInput;