2024-01-10 12:21:24 +05:30
|
|
|
import { useCallback } from "react";
|
|
|
|
|
|
|
|
|
|
type TUseDropdownKeyDown = {
|
2024-03-06 18:39:14 +05:30
|
|
|
(
|
|
|
|
|
onEnterKeyDown: () => void,
|
|
|
|
|
onEscKeyDown: () => void,
|
|
|
|
|
stopPropagation?: boolean
|
|
|
|
|
): (event: React.KeyboardEvent<HTMLElement>) => void;
|
2024-01-10 12:21:24 +05:30
|
|
|
};
|
|
|
|
|
|
2024-02-08 11:49:00 +05:30
|
|
|
export const useDropdownKeyDown: TUseDropdownKeyDown = (onEnterKeyDown, onEscKeyDown, stopPropagation = true) => {
|
2024-05-03 15:39:14 +05:30
|
|
|
const stopEventPropagation = useCallback(
|
|
|
|
|
(event: React.KeyboardEvent<HTMLElement>) => {
|
|
|
|
|
if (stopPropagation) {
|
|
|
|
|
event.stopPropagation();
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
[stopPropagation]
|
|
|
|
|
);
|
2024-02-08 11:49:00 +05:30
|
|
|
|
2024-01-10 12:21:24 +05:30
|
|
|
const handleKeyDown = useCallback(
|
|
|
|
|
(event: React.KeyboardEvent<HTMLElement>) => {
|
2025-06-09 19:37:42 +09:00
|
|
|
if (event.key === "Enter" && !event.nativeEvent.isComposing) {
|
2024-02-08 11:49:00 +05:30
|
|
|
stopEventPropagation(event);
|
2024-01-31 15:36:55 +05:30
|
|
|
onEnterKeyDown();
|
|
|
|
|
} else if (event.key === "Escape") {
|
2024-02-08 11:49:00 +05:30
|
|
|
stopEventPropagation(event);
|
2024-01-31 15:36:55 +05:30
|
|
|
onEscKeyDown();
|
2024-05-03 15:39:14 +05:30
|
|
|
} else if (event.key === "Tab") onEscKeyDown();
|
2024-01-10 12:21:24 +05:30
|
|
|
},
|
2024-02-08 11:49:00 +05:30
|
|
|
[onEnterKeyDown, onEscKeyDown, stopEventPropagation]
|
2024-01-10 12:21:24 +05:30
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return handleKeyDown;
|
|
|
|
|
};
|