mirror of
https://github.com/hydralauncher/hydra.git
synced 2025-01-23 21:44:55 +03:00
Merge pull request #75 from fernandozanutto/feat/close-modals-on-esc-or-outside-click
Feat/close modals on esc or outside click
This commit is contained in:
commit
f3c362e3f3
@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { XIcon } from "@primer/octicons-react";
|
||||
|
||||
@ -23,6 +23,8 @@ export function Modal({
|
||||
}: ModalProps) {
|
||||
const [isClosing, setIsClosing] = useState(false);
|
||||
const dispatch = useAppDispatch();
|
||||
const modalContentRef = useRef<HTMLDivElement | null>(null);
|
||||
const componentId = useId();
|
||||
|
||||
const handleCloseClick = () => {
|
||||
setIsClosing(true);
|
||||
@ -38,6 +40,42 @@ export function Modal({
|
||||
});
|
||||
};
|
||||
|
||||
const isTopMostModal = () => {
|
||||
const openModals = document.querySelectorAll("[role=modal]");
|
||||
return (
|
||||
openModals.length &&
|
||||
openModals[openModals.length - 1] === modalContentRef.current
|
||||
);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape" && isTopMostModal()) {
|
||||
handleCloseClick();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const onMouseDown = (e: MouseEvent) => {
|
||||
if (!isTopMostModal()) return;
|
||||
|
||||
const clickedOutsideContent = !modalContentRef.current.contains(
|
||||
e.target as Node
|
||||
);
|
||||
|
||||
if (clickedOutsideContent) {
|
||||
handleCloseClick();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("mousedown", onMouseDown);
|
||||
return () => window.removeEventListener("mousedown", onMouseDown);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(toggleDragging(visible));
|
||||
}, [dispatch, visible]);
|
||||
@ -46,7 +84,11 @@ export function Modal({
|
||||
|
||||
return createPortal(
|
||||
<div className={styles.backdrop({ closing: isClosing })}>
|
||||
<div className={styles.modal({ closing: isClosing })}>
|
||||
<div
|
||||
className={styles.modal({ closing: isClosing })}
|
||||
role="modal"
|
||||
ref={modalContentRef}
|
||||
>
|
||||
<div className={styles.modalHeader}>
|
||||
<div style={{ display: "flex", gap: 4, flexDirection: "column" }}>
|
||||
<h3>{title}</h3>
|
||||
|
Loading…
Reference in New Issue
Block a user