Skip to content

Commit

Permalink
🚑 - feat: allow enter key to submit date range picker
Browse files Browse the repository at this point in the history
  • Loading branch information
svenvandescheur committed Oct 11, 2024
1 parent 2f84852 commit bd8d860
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/components/form/dateinput/dateinput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ export const DateInput: React.FC<DateInputProps> = ({
const dateString = date2DateString(date);
dispatchEvent(dateString);
setIsPristine(false);
} else if (!isPristine) {
} else {
// Date is invalid after previous valid value, dispatch "".
dispatchEvent("");
setIsPristine(false);
Expand Down
41 changes: 34 additions & 7 deletions src/components/form/daterangeinput/daterangeinput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,31 @@ export const DateRangeInput: React.FC<DateRangeInputProps> = ({

const newValues = new Array(2);
newValues[index] = value;
newValues[flippedIndex] = _values[flippedIndex] || value;
newValues[flippedIndex] = _values[flippedIndex];
queuedValueState.current = newValues;
},
[queuedValueState.current],
);

/**
* Gets called when a keyUp event is received.
* Implements enter key change trigger..
*/
const handleKeyUp = useCallback<React.KeyboardEventHandler<HTMLInputElement>>(
(e) => {
if (e.key === "Enter") {
const dates = normalizeValuesState(queuedValueState.current)
?.map(value2Date)
.filter((v): v is Date => Boolean(v))
.map(date2DateString);

const dateString = dates?.length === 2 && dates.join("/");
dispatchEvent(dateString || "");
}
},
[queuedValueState.current, normalizeValuesState],
);

/**
* Gets called when a blur event is received.
* @param event
Expand All @@ -183,16 +202,24 @@ export const DateRangeInput: React.FC<DateRangeInputProps> = ({

const { currentTarget, relatedTarget } = e;
if (!relatedTarget || !currentTarget.contains(relatedTarget)) {
const newValuesState = normalizeValuesState(queuedValueState.current);
setValuesState(newValuesState);
const newValue = newValuesState?.join("/") || "";
dispatchEvent(newValue);
const dates = normalizeValuesState(queuedValueState.current)
?.map(value2Date)
.filter((v): v is Date => Boolean(v))
.map(date2DateString);

const dateString = dates?.length === 2 && dates.join("/");
dispatchEvent(dateString || "");
}
},
[document.activeElement, valuesState, normalizeValuesState],
[document.activeElement, queuedValueState.current, normalizeValuesState],
);
return (
<div ref={nodeRef} className="mykn-daterangeinput" onBlur={handleBlur}>
<div
ref={nodeRef}
className="mykn-daterangeinput"
onBlur={handleBlur}
onKeyUp={handleKeyUp}
>
<input
ref={fakeInputRef}
className="mykn-daterangeinput__input"
Expand Down

0 comments on commit bd8d860

Please sign in to comment.