2024-01-10 06:51:24 +00:00
|
|
|
import { useCallback } from "react";
|
|
|
|
|
|
|
|
type TUseDropdownKeyDown = {
|
2024-03-06 13:09:14 +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) => {
|
2024-05-03 10:09:14 +00:00
|
|
|
const stopEventPropagation = useCallback(
|
|
|
|
(event: React.KeyboardEvent<HTMLElement>) => {
|
|
|
|
if (stopPropagation) {
|
|
|
|
event.stopPropagation();
|
|
|
|
event.preventDefault();
|
|
|
|
}
|
|
|
|
},
|
|
|
|
[stopPropagation]
|
|
|
|
);
|
2024-02-08 06:19:00 +00:00
|
|
|
|
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-05-03 10:09:14 +00:00
|
|
|
} else if (event.key === "Tab") 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;
|
|
|
|
};
|