Skip to content

Commit edab60c

Browse files
committed
Refactor Input and add escape key handling for Datepicker
Simplified event handling logic in Input by reducing redundant checks and improving readability. Added a new feature in Datepicker to close the calendar on pressing the Escape key, enhancing user accessibility and navigation.
1 parent 94b0f14 commit edab60c

File tree

2 files changed

+40
-23
lines changed

2 files changed

+40
-23
lines changed

src/components/Datepicker.tsx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,24 @@ const Datepicker = (props: DatepickerType) => {
268268
}
269269
}, [asSingle, startFrom, value]);
270270

271+
useEffect(() => {
272+
const handleEscapeKey = (event: KeyboardEvent) => {
273+
const container = calendarContainerRef.current;
274+
275+
if (!container || !container.classList.contains("block") || event.key !== "Escape") {
276+
return;
277+
}
278+
279+
hideDatepicker();
280+
};
281+
282+
document.addEventListener("keydown", handleEscapeKey);
283+
284+
return () => {
285+
document.removeEventListener("keydown", handleEscapeKey);
286+
};
287+
}, [hideDatepicker]);
288+
271289
// Variables
272290
const safePrimaryColor = useMemo(() => {
273291
if (COLORS.includes(primaryColor)) {

src/components/Input.tsx

Lines changed: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -172,38 +172,37 @@ const Input = () => {
172172
useEffect(() => {
173173
const button = buttonRef?.current;
174174

175+
if (!button) return;
176+
175177
function focusInput(e: Event) {
176178
e.stopPropagation();
177179
const input = inputRef.current;
178180

179-
if (input) {
180-
input.focus();
181-
if (inputText) {
182-
changeInputText("");
183-
if (dayHover) {
184-
changeDayHover(null);
185-
}
186-
if (period.start && period.end) {
187-
changeDatepickerValue(
188-
{
189-
startDate: null,
190-
endDate: null
191-
},
192-
input
193-
);
194-
}
195-
}
181+
if (!input) return;
182+
183+
input.focus();
184+
185+
if (!inputText) return;
186+
187+
changeInputText("");
188+
if (dayHover) {
189+
changeDayHover(null);
190+
}
191+
if (period.start && period.end) {
192+
changeDatepickerValue(
193+
{
194+
startDate: null,
195+
endDate: null
196+
},
197+
input
198+
);
196199
}
197200
}
198201

199-
if (button) {
200-
button.addEventListener("click", focusInput);
201-
}
202+
button.addEventListener("click", focusInput);
202203

203204
return () => {
204-
if (button) {
205-
button.removeEventListener("click", focusInput);
206-
}
205+
button.removeEventListener("click", focusInput);
207206
};
208207
}, [
209208
changeDatepickerValue,

0 commit comments

Comments
 (0)