2024-01-10 06:51:24 +00:00
|
|
|
import { useCallback } from "react";
|
|
|
|
|
|
|
|
type TUseDropdownKeyDown = {
|
2024-02-08 06:19:00 +00:00
|
|
|
(onEnterKeyDown: () => void, onEscKeyDown: () => void, stopPropagation?: boolean): (
|
|
|
|
event: React.KeyboardEvent<HTMLElement>
|
|
|
|
) => void;
|
2024-01-10 06:51:24 +00:00
|
|
|
};
|
|
|
|
|
2024-02-08 06:19:00 +00:00
|
|
|
export const useDropdownKeyDown: TUseDropdownKeyDown = (onEnterKeyDown, onEscKeyDown, stopPropagation = true) => {
|
|
|
|
const stopEventPropagation = (event: React.KeyboardEvent<HTMLElement>) => {
|
|
|
|
if (stopPropagation) {
|
|
|
|
event.stopPropagation();
|
|
|
|
event.preventDefault();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-01-10 06:51:24 +00:00
|
|
|
const handleKeyDown = useCallback(
|
|
|
|
(event: React.KeyboardEvent<HTMLElement>) => {
|
|
|
|
if (event.key === "Enter") {
|
2024-02-08 06:19:00 +00:00
|
|
|
stopEventPropagation(event);
|
|
|
|
|
2024-01-31 10:06:55 +00:00
|
|
|
onEnterKeyDown();
|
|
|
|
} else if (event.key === "Escape") {
|
2024-02-08 06:19:00 +00:00
|
|
|
stopEventPropagation(event);
|
2024-01-31 10:06:55 +00:00
|
|
|
onEscKeyDown();
|
2024-01-10 06:51:24 +00:00
|
|
|
}
|
|
|
|
},
|
2024-02-08 06:19:00 +00:00
|
|
|
[onEnterKeyDown, onEscKeyDown, stopEventPropagation]
|
2024-01-10 06:51:24 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
return handleKeyDown;
|
|
|
|
};
|